Android Using Textwatcher To Replace Words
I have an editText, that you write in it something then when u click next .. the text u wrote gets written into another editText .. It's working perfectly .. But I want to use text
Solution 1:
Assign the Textwatcher to your editText then do something like
editText.setText(editText.getText().toString().replaceAll("S", "$"));
Here is the textWatcher with code applied
finalEditTextFirst= (EditText)findViewById(R.id.etFirst);
StringstrFirst= First.getText().toString();
finalTextViewdone= (TextView)findViewById(R.id.tvName);
StringstrDone= done.getText().toString();
ButtonTrans= (Button) findViewById(R.id.bTrans);
Trans.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
//First EditTextif (First.getText().toString().equals("John")) {
done.setText("JOHN");
} else {
if (First.getText().toString().equals("Ahmed")) {
done.setText("AHMED");
} else {
done.setText(First.getText());
}
}
};
});
First.addTextChangedListener(newTextWatcher() {
publicvoidonTextChanged(CharSequence s, int start, int before, int count) {
}
publicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
}
publicvoidafterTextChanged(Editable s) {
Stringtext= First.getText().toString();
text = text.replace('s', 'd'); // Any of the diffrent replace methods should work.
text = text.replace('S', '$'); // This uses the char replace method. Note, the ' quotations
text = text.replace('O', '@');
text = text.replace('o', '@');
done.setText(text);
}
});
Its possible that the error resided in the fact you are getting the old string again, and applying text.replace
on it. Rather than the modified string. I would have expected it to have got the new string, but setText doesnt seem to fire immediately.
So if you get the string into a variable, then apply all your changes. Then put it back to your text box it will work fine. (I have tested and working code here Pasted above
)
Solution 2:
When putting in the value of your first EditText into the value of the second EditText, you can use Java's replace()
function for Strings. For example, the following code prints "$X@$$".
Stringvalue="SXOSS";
StringnewValue= value.replace("S", "$"); //replaces all instances of S with $
newValue = newValue.replace("O", "@"); //replaces all instances of O with @
System.out.println(newValue);
Post a Comment for "Android Using Textwatcher To Replace Words"