我通常做的是:
1 - 创建一个新类,扩展我需要显示的偏好类型(每个偏好类型 1 个) 2 - 在其代码中,执行适当的操作以显示更新的摘要
3 - 在res/xml/preferences.xml文件
让我举一个小例子,对 EditTextPreference 有好处:
CLS_Prefs_Edit.java
/**
* CLS_Prefs_Edit class
*
* This is the class that allows for a custom EditTextPrefence
* (auto refresh summary).
*
* @category Custom Preference
* @author Luca Crisi (luca.crisi.lc@gmail.com)
* @copyright Luca Crisi
* @version 1.0
*/
package com.your_name.your_app;
/* -------------------------------- Imports --------------------------------- */
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public final class CLS_Prefs_Edit
extends EditTextPreference
{
/* ---------------------------- Constructors ---------------------------- */
public CLS_Prefs_Edit(final Context ctx, final AttributeSet attrs)
{
super(ctx, attrs);
}
public CLS_Prefs_Edit(final Context ctx)
{
super(ctx);
}
/* ----------------------------- Overrides ------------------------------ */
@Override
public void setText(final String value)
{
super.setText(value);
setSummary(getText());
}
}
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
>
<PreferenceCategory android:title="@string/pref_phone_cat">
<!-- NORMAL EditTextPreference, NO summary update -->
<!-- <EditTextPreference -->
<!-- android:widgetLayout="@layout/arr_dn" -->
<!-- android:key="phone" -->
<!-- android:title="@string/pref_phone_title" -->
<!-- android:summary="@string/pref_phone_summ" -->
<!-- android:defaultValue="" -->
<!-- android:inputType="phone" -->
<!-- android:digits="+1234567890" -->
<!-- /> -->
<!-- MY EditTextPreference, WITH summary update -->
<com.your_name.your_app.CLS_Prefs_Edit
android:widgetLayout="@layout/arr_dn"
android:key="phone"
android:title="@string/pref_phone_title"
android:summary="@string/pref_phone_summ"
android:defaultValue=""
android:inputType="phone"
android:digits="+1234567890"
/>
</PreferenceCategory>
</PreferenceScreen>
当然,在 /res/values/strings 中设置你的字符串,你就完成了。
请注意,此解决方案适用于 PreferenceFragments 和 PreferenceActivities。
我将它用于在 2.2 Froyo(显示 PreferenceActivity)和 4.4 KitKat(显示 PreferenceFragment)上运行的应用程序,
我希望它有所帮助。