【问题标题】:Change the color of a part of a TextView in strings.xml在 strings.xml 中更改 TextView 的一部分的颜色
【发布时间】:2020-10-16 14:59:12
【问题描述】:

在我的带有 Kotlin 的 android 应用程序中,我创建了一个布局,其中有一个 TextView 显示一些文本。对于文本,我在 strings.xml 中有一个项目,我想更改此文本部分的颜色,我尝试了以下代码:

<string name="description">the product is <font fgcolor="green"> free </font></string>

但是,颜色没有改变。 我只是想将“免费”的颜色更改为绿色,有人可以解释我如何实现这一点吗?

【问题讨论】:

    标签: android string textview


    【解决方案1】:

    请改用&lt;font color="#008000"&gt;free&lt;/font&gt;。根据the documentation,正确的属性名称是color,它只支持十六进制代码。

    【讨论】:

      【解决方案2】:

      Ben P. 的出色答案应该可以满足您的用例。但是,我想向您介绍另一种实现此目的的方法。

      你可以使用SpannableString来达到同样的效果。使用 SpannableString,您可以为字符串的任何部分设置多种行为(颜色、字体粗细、字体大小、点击行为等)。

      对于您问题中的字符串,您可以执行以下操作:

      // the textview you want to set your coloured text to
      TextView textView = (TextView) findViewById(R.id.myTextView);
      
      // declare the string you want to span as a Spannable
      Spannable wordtoSpan = new SpannableString("the product is free");  
      
      // set the colour span        
      wordtoSpan.setSpan(new ForegroundColorSpan(Color.GREEN), 15, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      
      // set the text to your TextView
      textView.setText(wordtoSpan);
      

      【讨论】:

        猜你喜欢
        • 2013-11-06
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        相关资源
        最近更新 更多