以编程方式将文本颜色设置为二次色
Set text color to secondary color programmatically
如何以编程方式将文本颜色设置为 "textColorSecondary"?我试过下面的代码,但它不起作用。有谁知道代码有什么问题吗?
TextView tv1 = ((TextView)v.findViewById(R.id.hello_world));
tv1.setTextColor(Color.textColorSecondary);
编辑:
要从属性中获取颜色,请使用:
TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.textColorSecondary, typedValue, true);
int color = typedValue.data;
首先在你的colors.xml
中添加textColorSecondary
<color name="textColorSecondary">PutColorCodeHere</color>
然后在代码中设置颜色:
tv1.setTextColor(getResource.getColor(R.color.textColorSecondary));
唯一对我有用的是这个实现:
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。
感谢 Anton Kovalyov 我根据 kotlin 开发人员的答案做了一些扩展功能。
fun Context.getAttrColor(@AttrRes attr: Int): Int {
val typedValue = TypedValue()
theme.resolveAttribute(attr, typedValue, true)
return typedValue.data
}
只要有上下文,就可以使用这个函数。
Material 设计库
提供了实用程序 class
@ColorInt val secondaryColor = MaterialColors.getColor(context, android.R.attr.textColorSecondary, Color.BLACK)
如何以编程方式将文本颜色设置为 "textColorSecondary"?我试过下面的代码,但它不起作用。有谁知道代码有什么问题吗?
TextView tv1 = ((TextView)v.findViewById(R.id.hello_world));
tv1.setTextColor(Color.textColorSecondary);
编辑:
要从属性中获取颜色,请使用:
TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.textColorSecondary, typedValue, true);
int color = typedValue.data;
首先在你的colors.xml
中添加textColorSecondary
<color name="textColorSecondary">PutColorCodeHere</color>
然后在代码中设置颜色:
tv1.setTextColor(getResource.getColor(R.color.textColorSecondary));
唯一对我有用的是这个实现:
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。
感谢 Anton Kovalyov 我根据 kotlin 开发人员的答案做了一些扩展功能。
fun Context.getAttrColor(@AttrRes attr: Int): Int {
val typedValue = TypedValue()
theme.resolveAttribute(attr, typedValue, true)
return typedValue.data
}
只要有上下文,就可以使用这个函数。
Material 设计库
提供了实用程序 class@ColorInt val secondaryColor = MaterialColors.getColor(context, android.R.attr.textColorSecondary, Color.BLACK)