【问题标题】:How to change text color of specific text in textview at runtime? [closed]如何在运行时更改文本视图中特定文本的文本颜色? [关闭]
【发布时间】:2017-01-19 03:24:03
【问题描述】:

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

我的名字是 Mohit Kumar。 Sachin 是我的榜样。我是 12 岁。目前我在 delhi 但我的家乡是 班加罗尔。

现在我想删除开始标签 和结束标签 并更改 android studio 中这些标签内的文本颜色。

我怎样才能做到这一点?

【问题讨论】:

  • 您应该提供您尝试过的代码并更好地组织您的问题,然后我们才能以更好的方式帮助您。
  • @Sagar Aghara 当您编辑问题时,请在提出建议之前关注内容。您试图删除他的要求
  • 欢迎来到 StackOverflow!请阅读用户指南,了解如何在发布问题之前提出好问题 (stackoverflow.com/help/how-to-ask) 谢谢

标签: android textview


【解决方案1】:

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

如果要为文本着色,可以使用 <font color='#EE0000'>TextYouWantToColor</font>,因此您需要将 替换为 <font color='#EE0000'> 并将 替换为 </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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      myTextView.setTextColor(Color.RED);
      

      【讨论】:

      • 这将为所有文本着色
      猜你喜欢
      • 2016-02-02
      • 2012-08-17
      • 2019-04-20
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多