Building a Custom Preference


The Android framework includes a variety of Preference subclasses that allow you to build a UI for several different types of settings. However, you might discover a setting you need for which there’s no built-in solution, such as a number picker or date picker. In such a case, you’ll need to create a custom preference by extending the Preference class or one of the other subclasses.

When you extend the Preference class, there are a few important things you need to do:

  • Specify the user interface that appears when the user selects the settings.
  • Save the setting's value when appropriate.
  • Initialize the Preference with the current (or default) value when it comes into view.
  • Provide the default value when requested by the system.
  • If the Preference provides its own UI (such as a dialog), save and restore the state to handle lifecycle changes (such as when the user rotates the screen).

The following sections describe how to accomplish each of these tasks.

Specifying the user interface

If you directly extend the Preference class, you need to implement onClick() to define the action that occurs when the user selects the item. However, most custom settings extend DialogPreference to show a dialog, which simplifies the procedure. When you extend DialogPreference, you must callsetDialogLayoutResourcs() during in the class constructor to specify the layout for the dialog.

For example, here's the constructor for a custom DialogPreference that declares the layout and specifies the text for the default positive and negative dialog buttons:

public class NumberPickerPreference extends DialogPreference {
public NumberPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs); setDialogLayoutResource(R.layout.numberpicker_dialog);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel); setDialogIcon(null);
}
...
}

Saving the setting's value

You can save a value for the setting at any time by calling one of the Preference class's persist*() methods, such as persistInt() if the setting's value is an integer or persistBoolean() to save a boolean.

Note: Each Preference can save only one data type, so you must use the persist*() method appropriate for the data type used by your custom Preference.

When you choose to persist the setting can depend on which Preference class you extend. If you extendDialogPreference, then you should persist the value only when the dialog closes due to a positive result (the user selects the "OK" button).

When a DialogPreference closes, the system calls the onDialogClosed() method. The method includes a boolean argument that specifies whether the user result is "positive"—if the value is true, then the user selected the positive button and you should save the new value. For example:

@Override
protected void onDialogClosed(boolean positiveResult) {
// When the user selects "OK", persist the new value
if (positiveResult) {
persistInt(mNewValue);
}
}

In this example, mNewValue is a class member that holds the setting's current value. Calling persistInt()saves the value to the SharedPreferences file (automatically using the key that's specified in the XML file for this Preference).

Initializing the current value

When the system adds your Preference to the screen, it calls onSetInitialValue() to notify you whether the setting has a persisted value. If there is no persisted value, this call provides you the default value.

The onSetInitialValue() method passes a boolean, restorePersistedValue, to indicate whether a value has already been persisted for the setting. If it is true, then you should retrieve the persisted value by calling one of the Preference class's getPersisted*() methods, such as getPersistedInt() for an integer value. You'll usually want to retrieve the persisted value so you can properly update the UI to reflect the previously saved value.

If restorePersistedValue is false, then you should use the default value that is passed in the second argument.

@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
// Restore existing state
mCurrentValue = this.getPersistedInt(DEFAULT_VALUE);
} else {
// Set default state from the XML attribute
mCurrentValue = (Integer) defaultValue;
persistInt(mCurrentValue);
}
}

Each getPersisted*() method takes an argument that specifies the default value to use in case there is actually no persisted value or the key does not exist. In the example above, a local constant is used to specify the default value in case getPersistedInt() can't return a persisted value.

Caution: You cannot use the defaultValue as the default value in the getPersisted*() method, because its value is always null when restorePersistedValue is true.

Providing a default value

If the instance of your Preference class specifies a default value (with the android:defaultValue attribute), then the system calls onGetDefaultValue() when it instantiates the object in order to retrieve the value. You must implement this method in order for the system to save the default value in the SharedPreferences. For example:

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInteger(index, DEFAULT_VALUE);
}

The method arguments provide everything you need: the array of attributes and the index position of theandroid:defaultValue, which you must retrieve. The reason you must implement this method to extract the default value from the attribute is because you must specify a local default value for the attribute in case the value is undefined.

Saving and restoring the Preference's state

Just like a View in a layout, your Preference subclass is responsible for saving and restoring its state in case the activity or fragment is restarted (such as when the user rotates the screen). To properly save and restore the state of your Preference class, you must implement the lifecycle callback methods onSaveInstanceState()and onRestoreInstanceState().

The state of your Preference is defined by an object that implements the Parcelable interface. The Android framework provides such an object for you as a starting point to define your state object: thePreference.BaseSavedState class.

To define how your Preference class saves its state, you should extend the Preference.BaseSavedStateclass. You need to override just a few methods and define the CREATOR object.

For most apps, you can copy the following implementation and simply change the lines that handle the value if your Preference subclass saves a data type other than an integer.

private static class SavedState extends BaseSavedState {
// Member that holds the setting's value
// Change this data type to match the type saved by your Preference
int value; public SavedState(Parcelable superState) {
super(superState);
} public SavedState(Parcel source) {
super(source);
// Get the current preference's value
value = source.readInt(); // Change this to read the appropriate data type
} @Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Write the preference's value
dest.writeInt(value); // Change this to write the appropriate data type
} // Standard creator object using an instance of this class
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
} public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}

With the above implementation of Preference.BaseSavedState added to your app (usually as a subclass of your Preference subclass), you then need to implement the onSaveInstanceState() andonRestoreInstanceState() methods for your Preference subclass.

For example:

@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
// Check whether this Preference is persistent (continually saved)
if (isPersistent()) {
// No need to save instance state since it's persistent,
// use superclass state
return superState;
} // Create instance of custom BaseSavedState
final SavedState myState = new SavedState(superState);
// Set the state's value with the class member that holds current
// setting value
myState.value = mNewValue;
return myState;
} @Override
protected void onRestoreInstanceState(Parcelable state) {
// Check whether we saved the state in onSaveInstanceState
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save the state, so call superclass
super.onRestoreInstanceState(state);
return;
} // Cast state to custom BaseSavedState and pass to superclass
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState()); // Set this Preference's widget to reflect the restored state
mNumberPicker.setValue(myState.value);
}
 

Android偏好设置(7)自定义Preference,和PreferenceDialog的更多相关文章

  1. Android的设置界面及Preference使用

    一般来说,我们的APP都会有自己的设置页面,那么其实我们有非常简单的制作方法.老样子,先看效果图. 然后就是看源代码了. 第一步,先在res文件夹中新建一个xml文件夹,用来存放preferences ...

  2. Android偏好设置(2)为应用定义一个偏好设置xml

    1.Defining Preferences in XML Although you can instantiate new Preference objects at runtime, you sh ...

  3. Android偏好设置(1)概述和Preferences简介

    1.Overview Instead of using View objects to build the user interface, settings are built using vario ...

  4. Android偏好设置(6)应用和监听各偏好参数

    Reading Preferences By default, all your app's preferences are saved to a file that's accessible fro ...

  5. Android偏好设置(5)偏好设置界面显示多个分组,每个分组也有一个界面

    1.Using Preference Headers In rare cases, you might want to design your settings such that the first ...

  6. Android偏好设置(4)设置默认值

    Setting Default Values The preferences you create probably define some important behaviors for your ...

  7. Android偏好设置(3)启动偏好设置后显示的界面PreferenceActivity和PreferenceFragment

    Creating a Preference Activity To display your settings in an activity, extend the PreferenceActivit ...

  8. 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener

    前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...

  9. MongoDB 读偏好设置中增加最大有效延迟时间的参数

    在某些情况下,将读请求发送给副本集的备份节点是合理的,例如,单个服务器无法处理应用的读压力,就可以把查询请求路由到可复制集中的多台服务器上.现在绝大部分MongoDB驱动支持读偏好设置(read pr ...

随机推荐

  1. 【甘道夫】并行化频繁模式挖掘算法FP Growth及其在Mahout下的命令使用

    今天调研了并行化频繁模式挖掘算法PFP Growth及其在Mahout下的命令使用,简单记录下试验结果,供以后查阅: 环境:Jdk1.7 + Hadoop2.2.0单机伪集群 +  Mahout0.6 ...

  2. Android进阶图片处理之三级缓存方案

    图片的三级缓存 一.概述 一開始在学习Android的时候.处理图片的时候,每次获取图片都是直接从网络上面载入图片. 可是在开发项目的过程中,每次点击进入app里面,图片都要慢慢的再一次从网络上面载入 ...

  3. 记一次Tomcat无法正常启动的查错与解决之路

    使用LombozEclipse运行某Web应用,结果总是404. 换另一个Eclipse运行,还是404. 换Tomcat到更高版本,还是404. 直接启动Tomcat,闪退. 用重定向拦截输出,可惜 ...

  4. 多媒体开发之wis-stream

    在live555的mediaServer中,已经实现RTSP-over-HTTP,但默认没有开启.如果要实现这个功能,需要调用RTSPServer::setUpTunnelingOverHTTP(), ...

  5. 记一次UICollectionView中visibleCells的坑

    记一次UICollectionView中visibleCells的坑 项目的要求是这样的 其实也是一个轮播图,而已,所以依照轮播图的实现原理,这里觉得也很简单,还是利用UICollectionView ...

  6. JAVA设计模式(01):创建型-工厂模式【工厂方法模式】(Factory Method)

    简单工厂模式尽管简单,但存在一个非常严重的问题.当系统中须要引入新产品时,因为静态工厂方法通过所传入參数的不同来创建不同的产品,这必然要改动工厂类的源码,将违背"开闭原则".怎样实 ...

  7. Android之——经常使用手机号码功能

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47374415 有些Android手机中会带有一些经常使用号码的功能,比方订餐电话. ...

  8. 转:目前为止最全的微信小程序项目实例

    wx-gesture-lock  微信小程序的手势密码 WXCustomSwitch 微信小程序自定义 Switch 组件模板 WeixinAppBdNovel 微信小程序demo:百度小说搜索 sh ...

  9. Android Studio集成Genymotion 及Genymotion 配置ADB

    1.打开 Android Studio,依次[File]-[Settings],快捷键  Ctrl + Alt + S 2.在打开的 settings 界面里找到 plugins 设置项,点击右侧的“ ...

  10. (2)mac下安装MySql数据库软件

    一,软件下载: https://dev.mysql.com/downloads/mysql/ 也可以从其他资源下载.不一定非要官方下载 二,安装 这个比较简单,之间双击开启安装程序,一直下一步就可以. ...