如何在运行时更改textview中特定文本的文本颜色?

时间:2017-01-19 03:24:04

标签: android textview

我以json对象的形式从服务器获取多个段落,如

  

我的名字是<(> Mohit Kumar<)>。 <(大于萨钦≤)>是我的榜样。我是   <(大于12≤)>岁。目前我在<(> delhi<)>但我的家乡是   <(大于班加罗尔≤)>

现在我要删除开始标记<(>和结束标记<)>并更改android studio中这些标签内的文本颜色。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

假设你得到了一个你提到的字符串,

如果您想为文字上色,可以使用<font color='#EE0000'>TextYouWantToColor</font>,因此您需要将&lt;(&gt; )替换为<font color='#EE0000'>&lt;)&gt; </font>

示例

public class YourActivity extends AppCompatActivity  {

  private  String yourString ;
  private  String yourNewString ;
  private  TextView tv ;
  private  String colorCodeStart = "<font color='#EE0000'>";  // use any color as  your want
  private  String colorCodeEnd = "</font>";


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

        tv = (TextView)findViewById(R.id.tv);

        yourString = "MY name is <(>Mohit Kumar<)>. <(>Sachin<)> is my role model. I am <(>12<)> year old. Currently i am in <(>delhi<)> but my hometown is <(>bangalore<)>.";
        yourNewString =  yourString.replace("<(>",colorCodeStart); // <(> and <)> are different replace them with your color code String, First one with start tag
        yourNewString=  yourNewString.replace("<)>",colorCodeEnd); // then end tag
        Log.d("CheckNew",yourNewString);
        tv.setText((Html.fromHtml(yourNewString))); 

    }


}

注意Html.fromHtml()已被弃用,替代方案是什么?查看here

enter image description here

答案 1 :(得分:0)

用空白字符替换标记,例如

String s = new String("<(>Change me<)>");
        s=s.replace("<(>","");
        s=s.replace("<)>","");

然后,要更改特定文本的TextColor,请使用SpannableString

SpannableString string = new SpannableString("Your string");
        string.setSpan(new StyleSpan(Typeface.BOLD), 1, 4, 0);
        string.setSpan(new ForegroundColorSpan(Color.GREEN), 5,string.length(), 0);

答案 2 :(得分:-1)

假设您使用的是TextView,请使用它来更改颜色:

myTextView.setTextColor(Color.RED);