任何人都可以建议我在更改CheckboxPreference或SwitchPrerence时执行AlertDialog以确认更改, 恩。如果我想取消选中Preference,AlertDialog应警告他们“你确定要取消选中吗?”加上对话框应该是可自定义的,因为我将使用自己的布局。我不想使用Dialog的Default Bluestrip Header。
SwitchPreference pref = (SwitchPreference) findPreference("prefkey_use_passcode");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
DialogPreference dialog = new DialogPreference(getParent());
return false;
}
});
答案 0 :(得分:4)
我设法这样做了:
final CheckBoxPreference myPref = (CheckBoxPreference) findPreference("myPref");
if (myPref != null) {
myPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue instanceof Boolean && ((Boolean) newValue) != PreferencesHelper.getMyPref()) {
final boolean isEnabled = (Boolean) newValue;
if (!isEnabled) {
new AlertDialog.Builder(PreferencesActivity.this)
.setTitle("Confirm")
.setIcon(R.drawable.alert)
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
})
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// OK has been pressed => force the new value and update the checkbox display
PreferencesHelper.setMyPref(false);
myPref.setChecked(false);
}
}).create().show();
// by default ignore the pref change, which can only be validated when OK is pressed
return false;
}
}
return true;
}
});
}
=> PreferencesHelper代码
public static boolean getMyPref() {
return getSharedPreferences().getBoolean("myPref", true);
}
public static void setMyPref(boolean newValue) {
Editor edit = getEditor();
edit.putBoolean("myPref", newValue);
edit.apply();
}
答案 1 :(得分:1)
这样的事情应该有效:
AlertDialog.Builder builder = new AlertDialog.Builder (this);
builder.setMessage (getString (R.string.are_you_sure));
builder.setNegativeButton (getString(android.R.string.cancel),
new DialogInterface.OnClickListener()
{
@Override
public void onClick (DialogInterface dialog, int which)
{
finish();
}
});
builder.setPositiveButton (getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
@Override
public void onClick (DialogInterface dialog, int which)
{
--- do the work to update the preference ---
finish();
}
});
builder.create().show();
return;