Highlighting Text Color using Html.fromHtml() in Android?

后端 未结 9 1353
忘了有多久
忘了有多久 2020-11-28 19:26

I am developing an application in which there will be a search screen where user can search for specific keywords and that keyword should be highlighted. I have found Html.f

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 20:10

    This can be achieved using a Spannable String. You will need to import the following

    import android.text.SpannableString; 
    import android.text.style.BackgroundColorSpan; 
    import android.text.style.StyleSpan;
    

    And then you can change the background of the text using something like the following:

    TextView text = (TextView) findViewById(R.id.text_login);
    text.setText("");
    text.append("Add all your funky text in here");
    Spannable sText = (Spannable) text.getText();
    sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
    

    Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

提交回复
热议问题