【问题标题】:Higlight Words in TextView在 TextView 中突出显示单词
【发布时间】:2015-03-10 20:12:08
【问题描述】:

我有一个 TextView 包含某个文本。是否可以每次更改TextView 中每个单词的背景?例如,先突出显示第一个字词,然后突出显示第二个字词,然后突出显示第三个字词,以此类推。

【问题讨论】:

标签: android


【解决方案1】:

是的,这是可能的。

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

More info here

Supported tags

Mutiple background color in one TextView

【讨论】:

  • OP想改变文本的背景。
  • 我可以用它来循环整个单词吗?
  • @EugenPechanec 我添加了一个用于添加多种背景颜色的链接
  • @user1950784 是的,有可能
【解决方案2】:
@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);
    }
}

【讨论】:

    【解决方案3】:

    是的,这是可能的。可以通过使用SpannableString 作为 TextView 内容来实现。您必须深入研究文档才能准确实现您想要的。在您的情况下使用的有用跨度之一是BackgroundColorSpan

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-14
      • 2018-02-08
      • 2014-08-07
      • 2012-11-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多