我的應用程序允許用戶爲每次啓動應用程序時選擇默認屏幕,並使用SharedPreferences來執行此操作。應用程序會在安裝後第一次啓動時提示他們選擇一個屏幕,並且該部分有效。但是,在允許用戶更改默認屏幕的應用程序中,我使用相同的代碼,並且它從不存儲更改。我需要改變什麼才能正確保存?允許用戶更改默認屏幕
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a Default Screen");
builder.setItems(R.array.openChoices, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("start", item);
editor.commit();
//Mech = 0, E&M = 1
int choice = getPreferences(0).getInt("start", 3);
if(choice == 0){
Toast.makeText(setscreen.this, "Mechanics is now the default screen", Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(setscreen.this, physics.class);
startActivity(myIntent);
}
else if(choice == 1){
Toast.makeText(setscreen.this, "E&M is now the default screen", Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(setscreen.this, physicsem.class);
startActivity(myIntent);
}
}
});
你有沒有試過調用editor.apply()? – Jack
不應該使用editor.commit()做同樣的事情嗎? – tedbrooks2
是的,文檔說他們也是這樣做的,我只是說它值得一試:)。 – Jack