即使应用关闭后如何保存复选框状态

时间:2017-01-27 21:29:42

标签: java android

大家好,请大家帮忙解决如何保存我的复选框状态,当我离开活动,刷新或关闭应用程序时,我的ckeckbox重置为未选中状态。我试着四处搜索,但我无法保存,下面是我的代码

    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;
    }
}

4 个答案:

答案 0 :(得分:1)

使用共享偏好设置:

要将数据写入共享首选项,请使用例如:

SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("checkbox", checkbox.isChecked())); //first value -preference name, secend value -preference value
editor.commit();

要阅读共享偏好设置:

SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
boolean isMyValueChecked = sharedPref.getBoolean("checkbox", false);//first value -preference name, secend value - default value if checbox not found

答案 1 :(得分:1)

在这里您可以看到有关此问题的完整Java编码:     在onCreate Method()中放入这些代码,您的问题将得到解决。我在这里的活动称为SettingsActivity。

    final SharedPreferences sharedPref = SettingsActivity.this.getPreferences(Context.MODE_PRIVATE);
    boolean isMyValueChecked = sharedPref.getBoolean("checkbox", false);

            CheckBox checkBox = (CheckBox) findViewById(R.id.chk_box_music);
    checkBox.setChecked(isMyValueChecked);
    checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putBoolean("checkbox", ((CheckBox) view).isChecked());
            editor.commit();
            if(checkBox.isChecked()){
                startService(new Intent(SettingsActivity.this, MyService.class));
            }else{
                stopService(new Intent(SettingsActivity.this, MyService.class));
            }
        }
    });

答案 2 :(得分:0)

每次更新时,您都可以将结果保存在SharedPreferences中。即使您的应用程序被杀,它也会存储在那里。您可以在每次再次启动活动时检查SharedPreferences中的值,并相应地设置检查。

设置SharedPreference:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

更新或编辑sharedPreferences,您可以在更新检查按钮时或在onClick期间添加此内容:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("checkBox1", true);
editor.commit();

您可以阅读sharedPreference:

Boolean defaultValue = sharedPref.getBoolean("checkBox1", defaultValue);

您还可以查看Android documentation或此tutorial

答案 3 :(得分:0)

你必须使用SharedPreferences作为Micha,skbrhmn和Sabriael建议你这样做。请按照以下链接中的指南来帮助您完成此操作。

https://developer.android.com/training/basics/data-storage/shared-preferences.html

有关SharedPreferences接口的更多详细信息......

https://developer.android.com/reference/android/content/SharedPreferences.html