我正在为自定义视图实现自己的 <declare-styleable>
(按照这里的说明)。 我想将整数数组指定为可能的 XML 属性之一。 我该如何:
- 在
attrs.xml
中将整数数组指定为 XML 属性? - 在我的自定义视图中调用
obtainStyledAttributes()
后从 TypedArray 中获取它?
我正在为自定义视图实现自己的 <declare-styleable>
(按照这里的说明)。 我想将整数数组指定为可能的 XML 属性之一。 我该如何:
attrs.xml
中将整数数组指定为 XML 属性?obtainStyledAttributes()
后从 TypedArray 中获取它?你可以将其声明为引用。
<declare-styleable name="MyView">
<attr name="array" format="reference"/>
</declare-styleable>
似乎TypeArray
没有getIntArray
方法,因此您必须直接从资源中获取它。
final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
final int id = array.getResourceId(R.styleable.MyView_array, 0);
if (id != 0) {
final int[] values = getResources().getIntArray(id);
}
array.recycle()
没有足够的声望来添加评论,只是想分享一下 Kotlin 的方式,其中扩展函数自己处理 recycle() 的调用。
context.withStyledAttributes(attrs, R.styleable.MyView, defStyleAttr) {
val resourceId = getResourceId(R.styleable.MyView_array, 0)
}