Set Text Color For A Specific Text In Android Edittext
If user types a String and it contains @ I want to change the color of the text to red. I have tried with textwatcher but got stack overflow error. I want to change the color only
Solution 1:
You have to remove the textwatcher before you set the new text to edit text. Try this code
privateTextWatchertextWatcher=newTextWatcher() {
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@OverridepublicvoidafterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
Stringtext= editText.getText().toString();
if (text .matches("(@\\w+)")) {
editText.setText(Html.fromHtml(text .replaceAll(
"(@\\w+)", "<font color='#ffff0000'>$1</font>")));
}
editText.addTextChangedListener(this);
}
};
Solution 2:
if (s.toString().matches("(@\\w+)"))
{
topic.setTextColor(Color.parseColor("#ffff0000"));
}
Solution 3:
Try this:
topic.addTextChangedListener(new TextWatcher() {
publicvoidonTextChanged(CharSequence s, int start, int before,
int count) {
}
publicvoidbeforeTextChanged(CharSequence s, int start, int count,
int after) {
}
publicvoidafterTextChanged(Editable s) {
if (s.toString().startsWith("@")) {
topic.setText(
Html.fromHtml("<font color='#ffff0000'>"+
s.toString().substring(1)
+"</font>"));
}
}
});
Solution 4:
if(s.toString().startsWith("@"))
{
topic.setTextColor(Color.RED);
}
Solution 5:
append to bring curser at end of line and set text null before appending
edt_customer_cc.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
}
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
}
@OverridepublicvoidafterTextChanged(Editable s) {
edt_customer_cc.removeTextChangedListener(this);
Stringtext= edt_customer_cc.getText().toString();
if (text .contains(";")) {
edt_customer_cc.setText("");
// append to bring curser at end of line
edt_customer_cc.append(Html.fromHtml(text.replaceAll(
"(\\;)", "<font color='#ff0000'>;</font>")));
}
//editText.setText(text);//editText.setSelection(text.length());
edt_customer_cc.addTextChangedListener(this);
}
});
Post a Comment for "Set Text Color For A Specific Text In Android Edittext"