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

如何通过代码获取?android:attr资源为动态RadioButton设置drawableEnd?

代码设置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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:57:15