如何通过代码获取?android:attr资源为动态RadioButton设置drawableEnd?
你遇到的问题核心是属性引用不匹配:XML中使用的是系统自带的?android:attr/listChoiceIndicatorSingle,但代码里错误引用了Material库的listChoiceIndicatorSingleAnimated属性,且该属性仅在Material主题下有效,导致资源找不到。
以下是正确的实现步骤和代码:
核心修正点
- 替换属性引用为系统属性
android.R.attr.listChoiceIndicatorSingle - 正确解析属性并设置drawable到RadioButton的drawableEnd位置
完整Kotlin代码示例
// 1. 创建RadioButton实例 val radioButton = RadioButton(this) // 2. 解析系统属性?android:attr/listChoiceIndicatorSingle val typedValue = TypedValue() if (theme.resolveAttribute(android.R.attr.listChoiceIndicatorSingle, typedValue, true)) { // 3. 获取对应的Drawable资源 val indicatorDrawable = ContextCompat.getDrawable(this, typedValue.resourceId) indicatorDrawable?.let { // 可选:设置Drawable的显示边界(根据需求调整大小) it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight) // 4. 设置到drawableEnd位置(用Relative方法适配RTL布局) radioButton.setCompoundDrawablesRelative(null, null, it, null) } } // 5. 将RadioButton添加到目标布局 yourContainerLayout.addView(radioButton)
额外说明
- 如果需要Material风格的动画单选图标,可以改用
com.google.android.material.R.attr.listChoiceIndicatorSingleAnimated,但必须确保当前Activity的主题继承自Material组件主题(如Theme.MaterialComponents.Light.DarkActionBar),否则会出现属性找不到的问题。 - 使用
setCompoundDrawablesRelative而非setCompoundDrawables,可以自动适配从右到左(RTL)的布局方向,提升兼容性。
内容的提问来源于stack exchange,提问作者wiryadev
相关产品推荐
相关产品推荐

