【问题标题】:Set text color to secondary color programmatically以编程方式将文本颜色设置为辅助颜色
【发布时间】:2015-06-07 18:45:42
【问题描述】:

如何以编程方式将文本的颜色设置为“textColorSecondary”?我已经尝试了下面的代码,但它不起作用。有人知道代码有什么问题吗?

TextView tv1 = ((TextView)v.findViewById(R.id.hello_world));
tv1.setTextColor(Color.textColorSecondary);

【问题讨论】:

  • 提问前必须搜索
  • 是的 MacaronLover,我只是建议在提问之前搜索 SO 可能是之前已经问过的重复问题
  • 我已经进行了搜索,但没有找到重复项,因此这就是我问它的原因。不管怎样,你知道它有什么问题吗?

标签: java android android-layout textview


【解决方案1】:

编辑:

要从属性中获取颜色,请使用:

TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.textColorSecondary, typedValue, true);
int color = typedValue.data;

【讨论】:

  • 使用后出现错误Cannot resolve symbol 'textColorSecondary'
  • 不,我认为 textColorSecondary 是一个属性?
  • 使用 android.R.attr.textColorSecondary
【解决方案2】:

真正对我有用的是这个实现:

int textColor = getTextColor(context, android.R.attr.textColorSecondary);

public int getTextColor(Context context, int attrId) {
    TypedArray typedArray = context.getTheme().obtainStyledAttributes(new int[] { attrId });
    int textColor = typedArray.getColor(0, 0);
    typedArray.recycle();
    return textColor;
}

这里的其他解决方案返回了错误的颜色 ID。

【讨论】:

    【解决方案3】:

    Material design library 提供了一个实用类

    @ColorInt val secondaryColor = MaterialColors.getColor(context, android.R.attr.textColorSecondary, Color.BLACK)
    

    【讨论】:

      【解决方案4】:

      感谢Anton Kovalyov我根据kotlin开发者的回答做了一些扩展功能。

      fun Context.getAttrColor(@AttrRes attr: Int): Int {
          val typedValue = TypedValue()
          theme.resolveAttribute(attr, typedValue, true)
          return typedValue.data
      }
      

      你可以在任何你有上下文的地方使用这个函数。

      【讨论】:

        【解决方案5】:

        首先在你的colors.xml中添加textColorSecondary

        <color name="textColorSecondary">PutColorCodeHere</color>
        

        然后在代码中设置颜色:

        tv1.setTextColor(getResource.getColor(R.color.textColorSecondary));
        

        【讨论】:

        • 非常感谢。你知道我的其他问题有什么问题吗?:link to other problem
        • 让我看看链接告诉你
        • 在我之前的评论中,链接到“链接到其他问题”
        • 我不会那样做的。您最终会得到两个具有相同名称的资源。 app.R.color.textColorSecondaryandroid.R.attr.textColorSecondary。您最好使用 TypeValue,如下面的答案。
        猜你喜欢
        • 1970-01-01
        • 2017-01-02
        • 2015-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-01
        • 2016-01-08
        • 1970-01-01
        相关资源
        最近更新 更多