我有一个Android PreferencesAcitivty,允许用户将他们的偏好设置重置为默认值。下面的代码工作正常,但在调用editor.clear()和editor.commit()之后,Preferences接口不会更新。如何在不重新加载活动或调用onCreate(null)的情况下实现此目的?
public class Preferences extends PreferenceActivity {
/* Called when someone specifies to view the options menu */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Set
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings, menu);
// Return
return true;
}
/* Handle options menu selections */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.itemReset:
// Reset
// Build
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
**// TODO: Refresh preferences**
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
// Display
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to reset your settings back to their default options?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
// Return
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
// Super
super.onCreate(savedInstanceState);
// Call
addPreferencesFromResource(R.xml.preferences);
}
}