我试图使用此方法获取工具栏textColor
:
private int getToolbarTextColor() {
int toolbarTextColor;
TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{R.attr.titleTextColor});
try {
toolbarTextColor = typedArray.getColor(0, Color.TRANSPARENT);
} catch (UnsupportedOperationException e) {
toolbarTextColor = Color.TRANSPARENT;
} finally {
typedArray.recycle();
}
return toolbarTextColor;
}
但它会返回0
。我的代码有什么问题?我应该使用什么属性?还有其他 更好的 方式来获取它吗?
答案 0 :(得分:3)
这是一种使用反射获取工具栏标题TextView的颜色的方法:
@ColorInt public static int getToolbarTitleTextColor(Toolbar toolbar) {
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
TextView mTitleTextView = (TextView) f.get(toolbar);
if (mTitleTextView != null) {
return mTitleTextView.getCurrentTextColor();
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;}
答案 1 :(得分:0)
val a = TintTypedArray.obtainStyledAttributes(context, null, R.styleable.Toolbar, R.attr.toolbarStyle, 0);
title.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))
subtitle.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))
(科特琳)