Вот пример того, как использовать настройку диалога (подклассы, как вы упомянули).
package dk.myapp.views;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
/**
* The OptionDialogPreference will display a dialog, and will persist the
* <code>true</code> when pressing the positive button and <code>false</code>
* otherwise. It will persist to the android:key specified in xml-preference.
*/
public class OptionDialogPreference extends DialogPreference {
public OptionDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
}
Файл Preferences.xml должен содержать
<dk.myapp.views.OptionDialogPreference
android:key="@string/prefKeyResetQuests"
android:dialogIcon="@android:drawable/ic_dialog_alert"
android:title="Reset Quests"
android:summary="Reset all quest-progress."
android:dialogMessage="Are you sure you wish to reset your quest progress? This action cannot be undone!"
android:positiveButtonText="Clear Quests"
android:negativeButtonText="Cancel"/>
У меня есть res / значение, содержащее (хотя имя ключа также может быть объявлено явно выше).
<string name="prefKeyResetQuests">resetQuests</string>
My PreferenceActivity выполняет фактический сброс с onPause.Обратите внимание, что onStop может быть слишком поздно, так как onStop не всегда будет вызываться сразу после нажатия:
@Override
public void onPause() {
SharedPreferences prefs = android.preference.PreferenceManager.
getDefaultSharedPreferences(getBaseContext());
if(prefs.getBoolean(
getResources().getString(R.string.prefKeyResetQuests), false)) {
// apply reset, and then set the pref-value back to false
}
}
Или эквивалентно, поскольку мы все еще в PreferenceActivity:
@Override
protected void onPause() {
Preference prefResetQuests =
findPreference(getResources().getString(R.string.prefKeyResetQuests));
if(prefResetQuests.getSharedPreferences().
getBoolean(prefResetQuests.getKey(), false)){
// apply reset, and then set the pref-value back to false
}
}