如何以编程方式设置Android RadioButton的buttonTint属性?
我来帮你搞定这个问题!在XML里用android:buttonTint设置RadioButton的着色很方便,但代码里确实没有直接对应的单一方法,不过分场景有几种可靠的实现方式:
1. 针对Android 5.0(API 21)及以上版本
从API 21开始,原生RadioButton提供了setButtonTintList()方法,你只需要传入一个ColorStateList对象就能实现着色。
方式一:直接使用颜色资源
RadioButton radioButton = findViewById(R.id.radio_payeer); // 获取颜色资源对应的ColorStateList ColorStateList tintList = ContextCompat.getColorStateList(this, R.color.colorPrimaryDark); // 设置着色 radioButton.setButtonTintList(tintList);
方式二:自定义选中/未选中的不同颜色
如果需要区分RadioButton选中和未选中时的颜色,可以手动构建ColorStateList:
RadioButton radioButton = findViewById(R.id.radio_payeer); ColorStateList tintList = new ColorStateList( new int[][]{ new int[]{-android.R.attr.state_checked}, // 未选中状态 new int[]{android.R.attr.state_checked} // 选中状态 }, new int[]{ getResources().getColor(R.color.unchecked_tint), // 未选中时的颜色 getResources().getColor(R.color.colorPrimaryDark) // 选中时的颜色 } ); radioButton.setButtonTintList(tintList);
2. 兼容Android 4.4(API 20)及以下版本
如果你的App需要兼容更低版本,建议使用AppCompatRadioButton(来自AndroidX库),它提供了向下兼容的着色方法:
第一步:XML中替换为AppCompatRadioButton
<androidx.appcompat.widget.AppCompatRadioButton android:id="@+id/radio_payeer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Payeer" />
第二步:代码中设置着色
AppCompatRadioButton radioButton = findViewById(R.id.radio_payeer); ColorStateList tintList = AppCompatResources.getColorStateList(this, R.color.colorPrimaryDark); // 使用兼容方法setSupportButtonTintList radioButton.setSupportButtonTintList(tintList);
小提示
ContextCompat和AppCompatResources能帮你处理不同版本的颜色资源获取逻辑,避免版本适配问题。- 如果你只需要统一的单一颜色,用第一种方式就足够;如果需要状态区分,自定义
ColorStateList会更灵活。
内容的提问来源于stack exchange,提问作者Sorwar Hossain Mostafa
相关产品推荐
相关产品推荐

