1.activity_main.xml
2.MainActivity.java
private CheckBox checkBox1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); output = (TextView) findViewById(R.id.output); checkBox1 = (CheckBox) findViewById(R.id.checkBox1); checkBox1.setChecked(getFromSP("cb1")); // checkBox讀取設定 checkBox_service.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { //監聽checkBox改變狀態 @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (checkBox1.isChecked()) { //如果有打勾(true) saveInSp("cb1", isChecked); // 儲存打勾設定 output.setText("啟動"); } else { //如果沒打勾(false) saveInSp("cb1", isChecked);// 儲存沒打勾設定 output.setText("關閉"); } } }); } /* 讀取設定 */ private boolean getFromSP(String key) { SharedPreferences preferences = getApplicationContext() .getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE); //PROJECT_NAME專案名,android.content.Context.MODE_PRIVATE默認設定 return preferences.getBoolean(key, false); //沒有key值時,回傳false } /* 儲存設定 */ private void saveInSp(String key, boolean value) { SharedPreferences preferences = getApplicationContext() .getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE); //PROJECT_NAME專案名,android.content.Context.MODE_PRIVATE默認設定 SharedPreferences.Editor editor = preferences.edit(); //建立SharedPreferences編輯器 editor.putBoolean(key, value); //利用編輯器加入屬性putBoolean(String key, boolean value),putFloat(String key, float value),putInt(String key, int value),putLong(String key, long value),putString(String key, String value) editor.commit(); //將數據儲存 }
參考來源:http://stackoverflow.com/questions/10016752/saving-checkbox-states
沒有留言 :
張貼留言