保存checkedtextview状态的问题,它与多个项目行为不当

问题描述 投票:1回答:1

我做了一个由CheckTextView和TextView组成的活动。当用户选中该框时,我想在用户离开活动或关闭应用程序时保存该状态。

我将onClickListener添加到每个CTV。

然后我尝试将其保存在onPause和onResume方法中。我无法解决这个问题因为复选框工作时我只保存了一些它的工作(它有所不同,但它适用于其中的1-5个)但是当我添加所有这些时,当我回到它们时它们不会被保存活动。

//this will always work and will save the state of the boxes


protected void onPause() {
        super.onPause();

        save(ctv1.isChecked());
        save(ctv2.isChecked());
        save(ctv3.isChecked());


}

protected void onResume() {
        super.onResume();


        ctv1.setChecked(load());
        ctv2.setChecked(load());
        ctv3.setChecked(load());
}


//when I add all of them, they are always either checked or unchecked
//it doesn't matter what combination of them I try, it seems that it is //always working with a couple of CTV's but fails with more than 5-6 of them



//this is how my onClickListener looks like

     CheckedTextView ctv1 = (CheckedTextView) findViewById(R.id.ctvFOX1);
      ctv1.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (ctv1.isChecked()) {
                  ctv1.setChecked(false);


              }
              else {
                  ctv1.setChecked(true);

              }
          }
      });




//save and load methods


private void save(final boolean isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.apply();
}

private boolean load() {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("check", false);
    }

java onresume onpause checkedtextview
1个回答
0
投票

因为您只使用一个键来保存CheckedTextView's值!

 private void save(final boolean isChecked, String key) {
        SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, isChecked);
        editor.apply();
    }

    private boolean load(String key) {
        SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(key, false);
    }

    protected void onPause() {
        super.onPause();
        save(ctv1.isChecked(), "check1");
        save(ctv2.isChecked(), "check2");
        save(ctv3.isChecked(), "check3");



    }

    protected void onResume() {
        super.onResume();
        ctv1.setChecked(load("check1"));
        ctv2.setChecked(load("check2"));
        ctv3.setChecked(load("check3"));

    }
© www.soinside.com 2019 - 2024. All rights reserved.