【问题标题】:How to keep the checked state of multiple checkboxes even after leaving the activity?即使离开活动,如何保持多个复选框的选中状态?
【发布时间】:2017-08-11 06:18:09
【问题描述】:

我真的需要一些帮助。即使搜索了几个小时并阅读了有关 SharedPreferences 的主题,我也无法解决我的问题。

即使我离开活动,我也希望复选框(多个复选框!)保持选中/取消选中状态。如果我回到原来的活动,复选框应该处于与以前相同的状态。 因此,您基本上可以将应用程序置于后台,如果您再次将其置于前台或转到另一个活动,则仍应选中/取消选中复选框(取决于用户选中的内容)。

这是我的 Activity.java 代码:

public class TennisActivity extends AppCompatActivity {
    //Variabeln
    CheckBox cb118;
    CheckBox cb119;
    CheckBox cb120;
    CheckBox cb121;
    CheckBox cb122;
    CheckBox cb123;
    CheckBox cb149;
    CheckBox cb150;
    CheckBox cb151;
    CheckBox cb152;
    CheckBox cb153;

    //Going back to menu by pressing back on device
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent homeIntent = new Intent(TennisActivity.this, SportActivity.class);
                startActivity(homeIntent);
                finish();
            }
        }, 1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_tennis);

        //Variabeln initalisiern
        cb118 = (CheckBox) findViewById(R.id.checkBox118);
        cb119 = (CheckBox) findViewById(R.id.checkBox119);
        cb120 = (CheckBox) findViewById(R.id.checkBox120);
        cb121 = (CheckBox) findViewById(R.id.checkBox121);
        cb122 = (CheckBox) findViewById(R.id.checkBox122);
        cb123 = (CheckBox) findViewById(R.id.checkBox123);
        cb149 = (CheckBox) findViewById(R.id.checkBox149);
        cb150 = (CheckBox) findViewById(R.id.checkBox150);
        cb151 = (CheckBox) findViewById(R.id.checkBox151);
        cb152 = (CheckBox) findViewById(R.id.checkBox152);
        cb153 = (CheckBox) findViewById(R.id.checkBox153);
    }
}

提前感谢您的帮助!

【问题讨论】:

    标签: java android android-activity checked android-checkbox


    【解决方案1】:

    当用户切换复选框时,使用Shared Preferences 保存当前状态。再次访问onCreate 后,您可以从中重新加载数据。

    要获得共享偏好:

    SharedPreferences sharedPref = 
    getActivity().getSharedPreferences("MY_SHARED_APPLICATIONS_NAME", Context.MODE_PRIVATE);
    

    写作:

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("MY_BOOL_VARIABLE_KEY", myBoolVariable);
    editor.commit();
    

    阅读:

    myBoolVariable = sharedPref.getBoolean("MY_BOOL_VARIABLE_KEY", defaultValue);
    

    对于您的特定情况,您将需要一个密钥来识别每个复选框,如下所示:

    private static final String cb118Key = "cb118_key";
    

    然后在初始化复选框后,您应该根据SharedPreferences上保存的内容设置它们的状态:

    cb118Checked = sharedPref.getBoolean(cb118Key, defaultValue);
    cb118.setChecked(cb118Key);
    

    唯一缺少的是在用户更改复选框状态时保存新状态:

    cb118.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor.putBoolean(cb118Key, isChecked);
            editor.commit();
        }
    });
    

    【讨论】:

    • 嘿 Natan,我对 Android Studio 还是很陌生。你能解释一下我必须在哪里写这些 SharedPreferences 吗?
    • 是的,我会这样做的——不过我仍在努力解决这个问题! :)
    • 我应该将那些 SharedPreferences 代码放在哪个方法中?我必须将这一切都纳入 onCreate-Methode 吗?它现在似乎可以工作,活动会记住选中的活动。但是,如果我选中它,该应用程序将关闭,但如果我重新打开它,复选框仍处于选中状态(如我所愿)。有没有可能私下给你写信? :)
    • 所有代码都应该在onCreate()之后调用,理想情况下你应该把它分解成更小的方法,比如loadInitialValues()setupCheckedChangedListeners()。如果您查看 Android Studio 的 logcat,您可以获得有关您遇到的错误的更多信息。
    【解决方案2】:

    在共享首选项中存储一个标志并检查值。如果它为真,则设置检查如下代码。

    String notif = pref.getString("notification", null);
    if (notif != null && notif.equalsIgnoreCase("true")){
                    checkBoxNotification.setChecked(true);
    
                }
    
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (checkBoxn.isChecked()) {
                            notification = "true";
                            editor.putString("notification", notification).commit();
    
                        } else {
                            notification = "false";
                            editor.putString("notification", notification).commit();
                        }
                    }
                });
    

    【讨论】:

      【解决方案3】:

      感谢 Natan,这是解决方案: (请注意,有一些导入 - 通常是自动 - 必须添加,例如 java.util.HashMap)

      //Variabeln
      CheckBox cb118;
      CheckBox cb119;
      CheckBox cb120;
      CheckBox cb121;
      CheckBox cb122;
      CheckBox cb123;
      CheckBox cb149;
      CheckBox cb150;
      CheckBox cb151;
      CheckBox cb152;
      CheckBox cb153;
      //TRY
      boolean myBoolVariable = false;
      private static final String cb118Key = "cb118_key";
      private static final String cb119Key = "cb119_key";
      private static final String cb120Key = "cb120_key";
      private static final String cb121Key = "cb121_key";
      private static final String cb122Key = "cb122_key";
      private static final String cb123Key = "cb123_key";
      private static final String cb149Key = "cb149_key";
      private static final String cb150Key = "cb150_key";
      private static final String cb151Key = "cb151_key";
      private static final String cb152Key = "cb152_key";
      private static final String cb153Key = "cb153_key";
      
      SharedPreferences sharedPref = null;
      
      
      //Zurück zu SportActivity
      @Override
      public void onBackPressed() {
          //super.onBackPressed();
          new Handler().postDelayed(new Runnable() {
              @Override
              public void run() {
                  Intent homeIntent = new Intent(TennisActivity.this, SportActivity.class);
                  startActivity(homeIntent);
                  finish();
              }
          }, 1);
      
      }
      
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      setContentView(R.layout.activity_tennis);
          setContentView(R.layout.activity_main);
      
      
      
          //Variabeln initalisiern
          cb118 = (CheckBox) findViewById(R.id.checkBox118);
          cb119 = (CheckBox) findViewById(R.id.checkBox119);
          cb120 = (CheckBox) findViewById(R.id.checkBox120);
          cb121 = (CheckBox) findViewById(R.id.checkBox121);
          cb122 = (CheckBox) findViewById(R.id.checkBox122);
          cb123 = (CheckBox) findViewById(R.id.checkBox123);
          cb149 = (CheckBox) findViewById(R.id.checkBox149);
          cb150 = (CheckBox) findViewById(R.id.checkBox150);
          cb151 = (CheckBox) findViewById(R.id.checkBox151);
          cb152 = (CheckBox) findViewById(R.id.checkBox152);
          cb153 = (CheckBox) findViewById(R.id.checkBox153);
      
          sharedPref = getSharedPreferences("alessionegrini.checkliste", Context.MODE_PRIVATE);
      
          // I'll turn that into a map so it's easy to iterate over the values
          Map<String, CheckBox> checkboxMap = new HashMap();
          checkboxMap.put(cb118Key, cb118);
          checkboxMap.put(cb119Key, cb119);
          checkboxMap.put(cb120Key, cb120);
          checkboxMap.put(cb121Key, cb121);
          checkboxMap.put(cb122Key, cb122);
          checkboxMap.put(cb123Key, cb123);
          checkboxMap.put(cb149Key, cb149);
          checkboxMap.put(cb150Key, cb150);
          checkboxMap.put(cb151Key, cb151);
          checkboxMap.put(cb152Key, cb152);
          checkboxMap.put(cb153Key, cb153);
      
          loadInitialValues(checkboxMap);
          setupCheckedChangeListener(checkboxMap);
      }
      
      public void loadInitialValues(Map<String, CheckBox> checkboxMap) {
          for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
              Boolean checked = sharedPref.getBoolean(checkboxEntry.getKey(), false);
              checkboxEntry.getValue().setChecked(checked);
          }
      }
      
      public void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) {
          for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
              checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                  @Override
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                      final SharedPreferences.Editor editor = sharedPref.edit();
                      editor.putBoolean(checkboxEntry.getKey(), isChecked);
                      editor.apply();
                  }
              });
          }
      }}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-29
        • 1970-01-01
        • 1970-01-01
        • 2019-09-12
        • 2012-08-25
        • 2016-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多