最近项目升级中,默认的prefedrence布局不能满足项目需求,于是必须自定义preference了,但遇到了些许问题,在此记录下来,希望大家共同进步。1
step1:新建一个layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/Btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/rBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
/>
<CheckBox
android:id="@+id/CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
step2:在setting.xml中指定自定义布局
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:key="noSetting" android:title="@string/setting_inout">
<fengyuun.Preference
android:dialogTitle="Dialog Title"
android:dialogMessage="Dialog summary"
android:key="@string/key_inte"
android:widgetLayout="@layout/preference"
/>
step 3:创建custom preferenceActivity,在这一步中,我首先想到的是实现一个类似于dialogpreference的组件,但查阅Api后发现这个组件无法调用getView方法,也就是所有的部件引用无法指定,为了解决这个问题,直接继承自preference,从而实现了getView和onBindView.
在构造函数中,要指定存储设置
setPersistent(true)// 允许保存设置
initCustomView();
onBindView()方法
void android.preference.Preference.onBindView(View view)
Binds the created View to the data for this Preference.
This is a good place to grab references to custom Views in the layout and set properties on them.
Make sure to call through to the superclass's implementation.
它可以绑定开一个view中的数据到preference,并且在后来的断点调试过程中,每次软件启动时,在此方法中可以解析得到preference中的数据,设置到当前的界面布局中。
需要注意的是一定要先执行超类方法,super.onBindView(view);
getView()方法,继承自preference,有两个形参,分别是转换的View和超类视图,返回一个preference object:
-
Parameters:
- convertView The old View to reuse, if possible. Note: You should check that this View is non-null and of an appropriate type before using. If it is not possible to convert this View to display the correct data, this method can create a new View.
- parent The parent that this View will eventually be attached to. Returns:
- Returns the same Preference object, for chaining multiple calls into a single statement.
-
-
View v = super.getView(convertView, parent);
v.findViewById(...)
最后要讲数值保存进setPage数据结构中,然后设置preferenceChengeListener()事件进行监听,保存和获得改变后的值。
callChangeListener(String);
这个方法的使用很重要,任何改变都需要设置这个方法才能通知到preferenceChengeListener()。
好了今天就到这里,下班了,大家工作愉快。