简体   繁体   English

仅以编程方式更改textview中某些文本的背景颜色

[英]Change background colour of some text within textview programmatically only

How can I change the background of some text within my view programmatically only using as few lines of code as possible? 如何仅使用尽可能少的代码行以编程方式更改视图中某些文本的背景? I tried to use the background tag within the html but unfortunately it doesn't support that hence is there any possible workaround to achieve something like the image below? 我试图在html中使用background标签,但是不幸的是它不支持,因此是否有任何可能的解决方法来实现类似下面的图像?

XML 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);
}

在此处输入图片说明

Try Spannable , something like: 试试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);

Your code is called from the UI thread (as it should be) but the call to Html.fromHtml(...) is very very expensive. 您的代码是从UI线程调用的(应该​​如此),但是对Html.fromHtml(...)的调用非常昂贵。 You can do it better by wrapping a couple of TextViews together in a LinearLayout and set each of separately. 您可以通过将几个TextViews封装在LinearLayout中并分别进行设置来更好地实现此目的。 It might not look nicer in first look but it much easier to maintain and saves cpu. 乍一看可能看起来不太好,但是维护起来更容易,而且可以节省CPU。 Especiallyif you intend to use this is a recyclerview or something. 特别是如果您打算使用,这是一个recyclerview之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM