You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取使用buttonBarNeutralButtonStyle的中性按钮标准颜色

获取ButtonBarNeutralButtonStyle对应的颜色值

嘿,我来帮你搞定这个问题!你想要提取?android:attr/buttonBarNeutralButtonStyle样式下按钮的颜色,不管是文本色还是背景色,这里有两种实用的方法:

方法一:直接从主题属性读取(推荐,无需依赖按钮实例)

这种方式不需要先找到按钮,直接从当前主题中解析样式对应的颜色,更高效:

// 获取主题中的buttonBarNeutralButtonStyle属性
TypedArray ta = getTheme().obtainStyledAttributes(new int[]{android.R.attr.buttonBarNeutralButtonStyle});
int styleResId = ta.getResourceId(0, 0);
ta.recycle();

// 从该样式中提取文本颜色(如果需要背景色,替换为android.R.attr.colorButtonNormal)
TypedArray styleTa = getTheme().obtainStyledAttributes(styleResId, new int[]{android.R.attr.textColor});
int textColor = styleTa.getColor(0, Color.BLACK); // 第二个参数是默认值
styleTa.recycle();

// 现在textColor就是你要的颜色,可以应用到其他视图
yourOtherView.setTextColor(textColor);

方法二:从已有的按钮实例中提取颜色

如果你已经拿到了按钮的实例,也可以直接从它身上获取当前生效的颜色:

View button = findViewById(R.id.passwordSigninButton);
if (button != null) {
    // 获取按钮的文本颜色
    int textColor = ((TextView) button).getCurrentTextColor();
    
    // 如果需要获取背景色(注意:如果背景是Drawable,需要判断类型)
    int backgroundColor = Color.TRANSPARENT;
    Drawable background = button.getBackground();
    if (background instanceof ColorDrawable) {
        backgroundColor = ((ColorDrawable) background).getColor();
    }
    
    // 应用到其他视图
    yourOtherView.setTextColor(textColor);
    // yourOtherView.setBackgroundColor(backgroundColor);
}

小提示

  • 如果你不确定样式控制的是文本色还是背景色,可以先查看系统的buttonBarNeutralButtonStyle定义,通常它会指定textColor和colorButtonNormal属性
  • 记得用完TypedArray后调用recycle(),避免资源泄漏

内容的提问来源于stack exchange,提问作者Ωmega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:15:45