Android:无法更改textview中部分文本的颜色

时间:2014-02-26 12:13:28

标签: android html textview spannable

嗨我试图将textview中的部分文本更改为某种颜色,但我无法实现它 我尝试了 fromHtml spannable 和不同的方法,但它仍无效。

我的尝试如下:

try1

    Spannable wordtoSpan = Spannable.Factory.getInstance().newSpannable("text 6 Months(180 days) or 8,000 kilometers.");

    wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    tv.setText(wordtoSpan);

try2

    String str = "@Second @Service:6 Months(180 days) or 8,000 kilometers.";

    String[] str_array = str .split(" ");

    boolean isExists = false;
    for (int i = 0; i < str_array.length; i++) {
             for (int j = 0; j < i; j++) {
                 if (str_array[j].equals(str_array[i])) {
                     isExists = true;
                 }
             }
             if (str_array[i].startsWith("@") && !isExists) {
                 str  = str .replace(str_array[i],
                         "<font color='#8A0A0A'>" + str_array[i]
                                 + "</font>");
             } else if (str_array[i].contains("#")) {
                 str  = str .replaceAll(str_array[i],
                         "<font color='#000000'><b>" + str_array[i]
                                 + "</b></font>");
             }
         }

         tv.setText(Html.fromHtml(str));
    }

try3

myTextView.setText(Html.fromHtml(text + "<font color=white>" + CepVizyon.getPhoneCode() + "</font><br><br>"
            + getText(R.string.currentversion) + CepVizyon.getLicenseText()));

try4

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //method1
        TextView tv = (TextView) findViewById(R.id.service);
        tv.setText(Html.fromHtml("<font color=\"#FFFFFF\">" + "give your string here long long longlong" + "</font>" + "<font color=\"#47a842\"></font>"));


        //method 2
        //SpannableStringBuilder WordtoSpan = new SpannableStringBuilder("give your string here long long longlong");
        //WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW),0,5,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //tv.setText(WordtoSpan);

    }

非常感谢任何帮助。谢谢你

2 个答案:

答案 0 :(得分:3)

试试这样。下面的代码非常适合我,我已经测试过了。

TextView ttt = (TextView) findViewById(R.id.textView11);
String styledText = "This is <font color='red'>simple</font>.";
ttt.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

这是输出。

enter image description here

答案 1 :(得分:0)

试试这个它在我的应用程序中完美运行..也可以帮助你

SpannableStringBuilder WordtoSpan = new SpannableStringBuilder(give your string here);
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW),starting Index, and the index of text from which you want to highlight you text,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView.setText(WordtoSpan);