Android获取非自定义属性值

以Spinner的entries属性为例

  1. 创建values/attrs.xml文件,添加下述代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="app">
        <attr name="android:entries" />
    </declare-styleable>
</resources>
  1. 获取属性
public AutoSpinner(Context context, AttributeSet attrs) {
    super(context, attrs);
    getAttrs(context, attrs);
}

private void getAttrs(Context context, AttributeSet attrs) {

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.app);
    if (ta.hasValue(R.styleable.app_android_entries)) {
        int array = ta.getResourceId(R.styleable.app_android_entries, 0);
        this.array = getResources().getStringArray(array);
    }

    ta.recycle();
}
  1. 在xml使用自定义控件
<com.jc.android.app.main.presentation.view.widget.AutoSpinner
    android:id="@+id/spinner_type"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:entries="@array/device_type"
    android:textSize="@dimen/text_size_sixteen"
    app:checkedValue="@={viewModel.deviceInfoModel.type}" />

以上就是获取自定义控件非自定义属性的写法

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容