2

嗨,我正在尝试将 textview 中的部分文本更改为某种颜色,但我无法实现它我尝试了 fromHtmlspannable和不同的方法,但它仍然无法正常工作。

我的尝试如下:

尝试1

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

尝试2

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

尝试3

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

尝试4

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

    }

非常感谢任何帮助。谢谢

4

2 回答 2

4

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

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

这是输出。

在此处输入图像描述

于 2014-02-26T12:15:55.430 回答
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);
于 2014-02-26T12:29:13.870 回答