以编程方式将文本颜色设置为辅助颜色

时间:2015-06-07 18:45:43

标签: java android android-layout textview

如何将文字的颜色设置为" textColorSecondary"编程?我已经尝试过以下代码,但它不起作用。有谁知道代码有什么问题?

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

5 个答案:

答案 0 :(得分:9)

修改:

要从属性获取颜色,请使用此选项:

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

答案 1 :(得分:2)

首先在colors.xml中添加textColorSecondary

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

然后在代码中设置颜色:

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

答案 2 :(得分:0)

真正对我有用的是此实现:

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 :(得分:0)

感谢 Anton Kovalyov,我根据 kotlin 开发人员的回答制作了一些扩展函数。

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

您可以在有上下文的任何地方使用此功能。

答案 4 :(得分:0)

有一个Material design library提供的实用类

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