2014-09-19 72 views
0

我目前正在開發一個具有菜單的應用程序,並且菜單中的一個選項是「設置」,用戶可以基本決定關閉聲音和其他類似的東西。我目前在設置活動中有兩個開關。下面是設置活動的Java代碼至今:Android保存在不同活動之間切換的值

public class Options extends ActionBarActivity { 
private Switch ding; 
private Switch countdown; 
public boolean isDingChecked; 
public boolean isCountdownChecked; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_options); 
    ding = (Switch) findViewById(R.id.switch1); 
    AppPreferences appPref; 
    appPref = new AppPreferences(getApplicationContext(), "PREFS"); 
    appPref.SaveData("Value", "Tag"); 
    appPref.getData("state"); 
    if(appPref.getData("state").equals("true")) 
    { 
     ding.setChecked(true); 
    } 
    else if(appPref.getData("state").equals("false")) 
    { 
     ding.setChecked(false); 
    } 
    ding.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if(ding.isChecked()) 
      { 
       ding.setChecked(true); 
      } 
     } 
    }); 
    countdown = (Switch) findViewById(R.id.switch2); 
    countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      // do something, the isChecked will be 
      // true if the switch is in the On position 
      isCountdownChecked = isChecked; 

     } 
    });  
} 
} 

但是,如果我回到菜單活動,然後回到選項活動,開關的值返回到默認值。有沒有辦法在不同的活動之間保存狀態?謝謝!

+0

檢查:HTTP://計算器.com/questions/24712821/sharedpreferemces-in-kitkat-version-in-android/24712877#24712877 – 2014-09-19 04:35:32

回答

3

您可以使用SharedPreferences。

商店吧:

SharedPreferences settings = getSharedPreferences("CoolPreferences", 0); 
SharedPreferences.Editor editor = settings.edit(); 
editor.putString("StringName", "StringValue"); 
// Commit the edits! 
editor.commit(); 

恢復它:

SharedPreferences settings = getSharedPreferences("CoolPreferences", 0); 
String silent = settings.getString("StringName", "DefaultValueIfNotExists"); 

你也可以把和恢復布爾和整數和其他... http://developer.android.com/reference/android/content/SharedPreferences.html

+0

你會保存它並在OnCreate方法中恢復它d?恢復會在聽衆中,還是隻能在存儲線之後? – user2677095 2014-09-20 01:50:07

+0

明白了!謝謝。 – user2677095 2014-09-20 05:30:42

+0

如果正確答案標記爲有效。 – CaptainTeemo 2014-09-22 01:39:06