今天看了一下checkboxPreference的实现,对如何引用到checkbox layout的一头雾水,于是好好补习了下style and theme ,也自己实现了一个自定义的preference 。
自定义Radiopreference的两种方法
1. 直接使用 widgetlayout属性指定 layout文件,这个是android 提供的接口 ,这种方式需要在每个radioPreference 中都要引用该layout,不详细记录。
2. 模仿checkboxPreference方式 定义控件。
步骤:
1. 在attrs.xml 中定义 该 控件对应的style名称,这个名称应该与theme中定义的相同,在checkbox的例子中就是 R.attr.checkBoxPreferenceStyle , 这里我们命名为 radioPreferenceStyle
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<resources>
<
declare-styleable
name
=
"RadioPreference"
>
<
attr
name
=
"radioPreferenceStyle"
format
=
"reference"
/>
<
attr
name
=
"radioPreference_summaryOn"
format
=
"reference"
/>
<
attr
name
=
"radioPreference_summaryoff"
format
=
"reference"
/>
</
declare-styleable
>
</
resources
>
2. 在 values/themes.xml中定义theme ,theme中增加 item 。该item的名字与attrs中的对应
<?xml version="1.0" encoding= "utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Light" >
<item name="radioPreferenceStyle" >@style/preference_radioButton</ item>
</style >
</resources>
3. 在values/styles.xml中定义具体的radioPreference 属性. 其实也是使用的widgetlayout 属性.
<resources xmlns:android="http://schemas.android.com/apk/res/android" >
<style name="preference_radioButton">
<item name="android:widgetLayout" >@layout/preference_radionbutton</ item>
</style >
</resources>
4. 在radioPreference中加载
public RadioPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.RadioPreference, defStyle, 0);
a.recycle();
}
public RadioPreference(Context context, AttributeSet attrs) {
//radioPreferenceStyle 定义了radiopreference的样式引用。
this(context, attrs, R.attr.radioPreferenceStyle);
}
public RadioPreference(Context context) {
this(context, null);
}