Android开发中无法获取自定义属性值,始终返回默认值该如何解决
Android自定义View获取自定义属性始终返回默认值解决方案
- 检查自定义属性声明是否正确
要在res/values/attrs.xml中正确声明<declare-styleable>标签,示例:
要保证属性名和代码里引用的<declare-styleable name="CustomView"> <attr name="secondHandColor" format="color" /> </declare-styleable>R.styleable.CustomView_xxx后缀完全一致,format和你获取的类型匹配,颜色类型就对应getColor方法。 - 检查XML布局中属性引用的命名空间是否正确
自定义属性必须使用APP自定义命名空间,不能用android原生命名空间,示例:<com.yourpackage.CustomView xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" app:secondHandColor="#FF0000" /> - 检查自定义View构造函数是否正确传递AttributeSet参数
如果是用Kotlin的@JvmOverloads写构造函数,要保证defStyleAttr默认传0,且把attrs参数传递给setupAttributes方法,正确构造函数示例:class CustomView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { init { setupAttributes(attrs) } // 其余逻辑 } - 必须调用TypedArray的recycle方法回收资源
现有代码缺失TypedArray回收步骤,未回收可能导致属性读取异常,修正后的setupAttributes代码:private fun setupAttributes(attrs: AttributeSet?) { val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0) try { mColor = typedArray.getColor(R.styleable.CustomView_secondHandColor, Color.CYAN) paint.color = mColor } finally { typedArray.recycle() } } - 检查是否存在样式覆盖问题
如果CustomView在布局中引用了style,或者Application/Activity主题中指定了该View的默认样式,要确认对应样式中没有覆盖该自定义属性。
内容的提问来源于stack exchange,提问作者Ярослав
相关产品推荐
相关产品推荐

