【发布时间】:2018-03-19 14:17:01
【问题描述】:
我正在使用 style="?android:attr/buttonBarNeutralButtonStyle" 的按钮
<Button
style="?android:attr/buttonBarNeutralButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Sign in" />
我想获得它的颜色,所以我也可以将它与其他视图元素一起使用。
目前我正在像这样读取它的颜色值:
int color;
View button = findViewById(R.id.passwordSigninButton);
if ((button != null) && (button instanceof Button))
color = ((Button) button).getCurrentTextColor();
// -16738680
...它工作正常。但我更愿意直接获取与适用样式关联的颜色,而不需要使用实际按钮,以防我想在布局中没有按钮的情况下使用它。
所以我尝试了这种方法:
TypedValue typedValue = new TypedValue();
getApplicationContext().getTheme().resolveAttribute(
android.R.attr.buttonBarNeutralButtonStyle, typedValue, true);
TypedArray typedArray = context.obtainStyledAttributes(
typedValue.data, new int[]{android.R.attr.textColor});
int color = typedArray.getColor(0, -1);
// -1
typedArray.recycle();
但是我得到了-1,这意味着我没有得到我期望的颜色。
如何从android.R.attr.buttonBarNeutralButtonStyle 样式中获取颜色?
【问题讨论】:
-
你的
minSdkVersion是什么。我假设它至少是 21,因为您使用的是 API 21 中引入的buttonBarNeutralButtonStyle。此外,正在使用支持库,因此您的按钮是否属于AppCompatButton类型? -
@Cheticamp - 我的
minSdkVersion是 23 岁。有关其他详细信息,请参阅 pastebin.com/raw/Xs6LCrka。 -
谢谢。您使用的是
AppCompatButton还是非兼容按钮?我认为这很重要。 -
我在您的 pastebin 文件中看到了
appcompat-v7:26.1.0,所以我假设您使用的是AppCompatButton,但您能确认一下吗? -
@Cheticamp - 测试代码在布局中不包含任何按钮,因此应该没有任何区别。
标签: java android android-layout android-resources android-theme