Android Developer
Android Developer

Reputation: 987

How to replace the particular word with changing text color in edittext

String text="Android is a operating system for mobile. Android latest version is kitkat.";

I have two edittext. the first edittext is used to search the text. The second edittext is used to display the text.

If i am entered the android in first edittext it search the String text and display the result in second edittext. Now mu question is how to replace the Android text with changing the color of Android text only.
Eg:Android(red color) is a operating system for mobile. Android(red color) latest version is kitkat.

I tried with String ss=text.replaceAll(Android font color=\"red\" + Android + "/font
this code.
edtresult.setText(Html.fromHtml(ss).
Html removes all the spaces

Thanks in advance

Upvotes: 0

Views: 1328

Answers (2)

QArea
QArea

Reputation: 4981

You can try Spannable like this:

EditText et = (EditText) findViewById(R.id.edit_text);
        SpannableString ss = new SpannableString("Android is a operating system for mobile. Android latest version is kitkat.");
        String textToSearch = "Android";
        Pattern pattern = Pattern.compile(textToSearch);
        Matcher matcher = pattern.matcher(ss);
        while (matcher.find()) {
            ss.setSpan(new ForegroundColorSpan(Color.RED), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
et.setText(ss);

Upvotes: 3

Veaceslav Gaidarji
Veaceslav Gaidarji

Reputation: 4301

You can use Spannables as described here

Upvotes: 1

Related Questions