需求:
4.2 原生的catagory通常 是一个title, 一条线, 通常是黑色的或白色的线, 现在有一个需求是 改变title的颜色,改变横线颜色的值。
1. 先定义这个category 的布局(布局里没有设置颜色值, 我们将在代码中设置颜色, 当然, 在 xml里也可以设置颜色):
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical" ><TextViewandroid:id="@+id/preference_title"android:layout_marginTop="1dip"android:layout_marginBottom="1dip"android:layout_width="match_parent"android:layout_height="wrap_content"/><Viewandroid:id="@+id/preference_divider"android:layout_width="match_parent"android:layout_height="1dip"/></LinearLayout>
2. 给自定义的 category 自定义两个属性, 一个是标题, 一个是分隔线:
<declare-styleable name="PreferenceStyle"><attr name="divider" format="dimension" /><attr name="title" format="string" /></declare-styleable>
3. 自定义ContactsPreferenceCategory :
public class ContactsPreferenceCategory extends PreferenceCategory {private String mTitle;private int mColor;public ContactsPreferenceCategory(Context context, AttributeSet attrs) {super(context, attrs);TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PreferenceStyle);mColor = a.getInt(R.styleable.PreferenceStyle_divider, getContext().getResources().getColor(R.color.call_log_voicemail_highlight_color));mTitle = a.getString(R.styleable.PreferenceStyle_title); a.recycle();}protected View onCreateView(ViewGroup parent) {return LayoutInflater.from(getContext()).inflate(R.layout.contacts_category, parent, false);}@Overrideprotected void onBindView(View view) {Log.i("huangbozhi", "class:" + view.getClass());super.onBindView(view);//在这里设置颜色值和字体大小TextView tv = (TextView) view.findViewById(R.id.preference_title);tv.setTextSize(16);tv.setTextColor(getContext().getResources().getColor(R.color.call_log_voicemail_highlight_color));tv.setText(mTitle);//设置线的颜色View divider = (View) view.findViewById(R.id.preference_divider);divider.setBackgroundColor(mColor);}
4. 在preference 里引用自定义的category, 注意命名空间, 我这里写的是 xmlns:preference="/apk/res/com.android.contacts",
因为我的包名是com.android.contacts, 所以引用属性就引用为preference:title
<PreferenceScreen xmlns:android="/apk/res/android"xmlns:preference="/apk/res/com.android.contacts"><com.android.contacts.preference.ContactsPreferenceCategory preference:title="@string/about"><Preferenceandroid:key="help"android:title="@string/help" ></Preference></com.android.contacts.preference.ContactsPreferenceCategory></PreferenceScreen>
5. category 对比(其实没改变什么, 就是把颜色改了而已):