2015-07-11 183 views
1

如何以编程方式更改我的视图中某些文本的背景只使用尽可能少的代码行?我试图在HTML中使用背景标签,但不幸的是它不支持,因此是否有任何可能的解决方法来实现像下面的图像?以编程方式更改textview中某些文本的背景颜色

XML

<TextView 
    android:id="@+id/main_textView0" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    style="@android:style/TextAppearance.Medium"/> 

的Java

@Override 
public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
    View v = getView(); 

    TextView txt = (TextView)v.findViewById(R.id.main_textView0); 
    txt.setText(Html.fromHtml("<font color='#0099CC'>" + getResources().getString(R.string.hello) + "</font>" + 
        " " + 
        "<font color='#000000'>" + getResources().getString(R.string.world) + "</font>" 
    )); 

    super.onActivityCreated(savedInstanceState); 
} 

enter image description here

+0

的HTML的方法可能是在这种情况下,唯一的解决办法。 – Egor

+1

我建议你使用https://android-arsenal.com/网站,它有库 –

回答

5

尝试Spannable,是这样的:

  String str1 = "Hello"; 
      String str2 = "world"; 
      String message = str1 + " " + str2; 

      Spannable spannable = new SpannableString(message); 
      spannable.setSpan(new ForegroundColorSpan(Color.BLUE),0, str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

      textView.setText(spannable); 
+2

正确,然后用BackgroundColorSpan做同样的事情。 – BladeCoder

+0

@BladeCoder如何设置str2的前景色?我只是简单地将它添加到底下,还是我需要添加另一个Spannable? – MacaronLover

+0

我认为str2具有TextView的默认文本颜色。你可以使用TextView.setTextColor() – BladeCoder

0

你的代码是从UI线程调用(因为它应该是),但调用HTML。 fromHtml(...)是非常非常耗费即 通过在LinearLayout中包装几个TextView并分别设置每个TextView,可以做得更好。它看起来可能不会看起来更好,但维护和保存cpu更容易。 特别是你打算使用这是一个recyclerview什么的。

相关问题