Android获取非自定义属性值

2017-11-27  本文已影响86人  费城的二鹏

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

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

上一篇 下一篇

猜你喜欢

热点阅读