搜索
您的当前位置:首页正文

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}" />

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

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

热门图文

Top