0

I have a TextView that holds a certain Text. Is it possible to change the background of each word in the TextView every amount of time? For example, highlight the first word then second then third and so on.

3dgoo
  • 15,716
  • 6
  • 46
  • 58
Rashad.Z
  • 2,494
  • 2
  • 27
  • 58
  • I guess you should embed html in your class file. Otherwise not possible. – Apurva Mar 10 '15 at 20:14
  • can you please explain what you mean or give me a link for more info – Rashad.Z Mar 10 '15 at 20:15
  • possible duplicate of [Custom TextView in android with different color words](http://stackoverflow.com/questions/11479560/custom-textview-in-android-with-different-color-words) – Phantômaxx Mar 10 '15 at 20:15

3 Answers3

2

Yes, it's possible.

String html = "hello <font color='#ff0000'>there</font>";
textView.setText(Html.fromHtml(html));

More info here

Supported tags

Mutiple background color in one TextView

Community
  • 1
  • 1
frogatto
  • 28,539
  • 11
  • 83
  • 129
1
@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.my_text_view);
    textView.setText("Hello there");
    mMyRunnable.start = 0;
    mMyRunnable.text = textView.getText().toString();
    mHandler = new Handler();
    mHandler.postDelayed(mMyRunnable, 1000);
}

private MyRunnable mMyRunnable = new MyRunnable();

private class MyRunnable implements Runnable{

    String text;
    int start = 0;

    @Override
    public void run () {
        //get the next index of space..notice that this answer assumes that there are no double sapces
        final int end = text.indexOf(32, start);

        Spannable wordSpan = new SpannableString(text);

        //case this is the last word
        if(end == -1){
            wordSpan.setSpan(new ForegroundColorSpan(Color.CYAN), start, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        //color the current word, set start end start handler again
        else{
            wordSpan.setSpan(new ForegroundColorSpan(Color.CYAN), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = end + 1;
            mHandler.postDelayed(mMyRunnable, 1000);
        }

        textView.setText(wordSpan);
    }
}
royB
  • 12,779
  • 15
  • 58
  • 80
0

Yes, it is possible. It can be achieved by using SpannableString as TextView contents. You'll have to dive into documentation to achieve exactly what you want. One of the usefull spans to use in your case is BackgroundColorSpan

Kirill K
  • 771
  • 6
  • 17