【问题标题】:Set color to string programatically in android?在android中以编程方式将颜色设置为字符串?
【发布时间】:2013-12-17 06:57:36
【问题描述】:

我有很多字符串要加载到列表视图中,我需要将文本颜色设置为字符串

我google了很多,但我只有一个

textView.setTextColor(getResources().getColor(R.color.red));

我没有使用 textview 我只是将字符串直接加载到 listview 中

有人建议这样做

String s="Hello World";
SpannableString ss=  new SpannableString(s);                
ss.setSpan(new ForegroundColorSpan(Color.GREEN), 0, 5, 0);  

但它不适合我

如有任何建议,请提前谢谢

【问题讨论】:

  • 你在使用类似这样的适配器吗?...new ArrayAdapter(this, android.R.layout.simple_list_item_1, testArray);
  • 您正在使用 TextView。没有办法“直接将字符串加载”到列表视图中。
  • 那你如何加载字符串?

标签: android performance android-layout listview


【解决方案1】:

下面的代码将TextView 中的文本设置为"Hello World",其中"Hello" 为红色,"World" 为绿色。

TextView myTextView = new TextView(this);
SpannableString myStr1 = new SpannableString("Hello");
SpannableString myStr2 = new SpannableString("World");
myStr1.setSpan( new ForegroundColorSpan(Color.RED), 0, myStr1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myStr2.setSpan( new ForegroundColorSpan(Color.GREEN), 0, myStr2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myTextView.setText(TextUtils.concat(myStr1, " ", myStr2);

【讨论】:

    【解决方案2】:
    StringBuilder sb = new StringBuilder();
    sb.append(" <font color='red'>");
    sb.append("Hello World");
    sb.append("</font>");
    textView.setText(Html.fromHtml(sb.toString()));
    

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      如果你想改变 textview 文本的颜色意味着像这样使用

           textView.setTextColor(Color.parseColor("#123123")); // give your own text color here
      

      它会起作用的。

      【讨论】:

        猜你喜欢
        • 2015-09-20
        • 1970-01-01
        • 2013-07-23
        • 1970-01-01
        • 2015-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-08
        相关资源
        最近更新 更多