自定义首选项中的Android自定义资源标识

时间:2014-07-16 10:37:26

标签: android android-preferences

我已经开始开发自定义偏好:

<com.package.lib.android.preference.CustomPreference
    xmlns:customPreference="http://schemas.android.com/apk/src/com.package.lib.android.preference.CustomPreference"
    android:key="test"
    android:title="test"
    customPreference:minValue="4" />

相关课程:

public class CustomPreference extends DialogPreference {
    private Context mContext;
    private LayoutInflater mLayoutInflater;

    public CustomPreference(final Context context, final AttributeSet attrs) {
        super(context, attrs);

        mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);

        // how can I access customPreference:minValue?
    }
}

在我的CustomPreference课程中,我想访问customPreference:minValue。怎么可能?

1 个答案:

答案 0 :(得分:1)

我明白了。

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:customPreference="http://schemas.android.com/apk/res-auto" >

    <com.package.lib.android.preference.CustomPreference
        android:defaultValue="@integer/font_size_default_value"
        android:key="test"
        android:title="title"
        customPreference:minValue="@integer/font_size_min_value"
        customPreference:maxValue="@integer/font_size_max_value" />

attrs.xml文件夹中创建一个res/values文件,其中包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="CustomPreference">
        <attr name="minValue" format="integer" />
        <attr name="maxValue" format="integer" />
    </declare-styleable>

</resources>

在首选项类中,您可以使用以下方式获取属性:

final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomPreference);

Log.i(TAG, String.valueOf(a.getInt(R.styleable.CustomPreference_minValue, 0)));
Log.i(TAG, String.valueOf(a.getInt(R.styleable.CustomPreference_maxValue, 100)));

a.recycle();