你好任何人都可以請幫助我如何保存我的複選框狀態,當我離開活動,刷新或關閉應用程序我的cckckbox重置爲取消選中。我嘗試四處搜索,但無法保存,下面是我的代碼如何保存複選框的狀態,即使應用程序關閉
package com.example.android.xb;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class RemindersActivity extends AppCompatActivity {
Calendar calender = Calendar.getInstance();
private TextView timePicker;
private int pHour;
private int pMinute;
static final int TIME_DIALOG_ID = 0;
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
pHour = hourOfDay;
pMinute = minute;
updateDisplay();
}
};
private void updateDisplay() {
timePicker.setText(new StringBuilder()
.append(pad(pHour)).append(":")
.append(pad(pMinute)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminders);
// Display for up button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Setting up the onlick listener
findViewById(R.id.checkbox_alert).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (((CheckBox) view).isChecked()) {
// Time setup for notification to pop up
calender.set(Calendar.HOUR_OF_DAY, pHour);
calender.set(Calendar.MINUTE, pMinute);
// Setting up the notification on checkbox checked
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),
alarmManager.INTERVAL_DAY, pendingIntent);
}
}
});
// Setting up the onclick listener for time textView
timePicker = (TextView) findViewById(R.id.time_set);
timePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
final Calendar calendar = Calendar.getInstance();
pHour = calendar.get(Calendar.HOUR_OF_DAY);
pMinute = calendar.get(Calendar.MINUTE);
updateDisplay();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, pHour, pMinute, false);
}
return null;
}
}
這就是SharedPreferences是。他們被寫入文件系統。 – Micha