简体   繁体   中英

Android-Making checkbox state stable even after closing the application:

I used onCheckedChanged method to handle the checkboxes.Its working well when i clicked.After leaving or closing the application and when i reopening it,the checkboxes state remains disabled.I want my checkboes state as i clicked(checked/unchecked) even after closing the application and reopening it.I tried using sharedpreferences posted here to achieve it.But as i am not cleared about it,i couldn't.

viewHolder.checkbox
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {


                        Model element = (Model) viewHolder.checkbox
                                .getTag();
                        element.setSelected(buttonView.isChecked());


   Interactivearrayadapter.this.putBooleanInPreferences(isChecked,"isChecked");
 }
  });
  }

 public void putBooleanInPreferences(boolean isChecked,String key){
    SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, isChecked);
    editor.commit();        
}
public boolean getBooleanFromPreferences(String key){
    SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
    Boolean isChecked = sharedPreferences.getBoolean(key, false);
    return isChecked;   

I used this code inside Interactivearrayadapter class since i displayed checkboxes in a list.Error shows in getpreference(string) not support to this class.

sharedpreferences存储您的复选框ischecked()标志,并在下次启动应用程序时获取该标志并显示。

Use a preference for each checkbox. If the activity is displayed read the preference and check or uncheck the checkbox (eg in onResume()). Register an OnClickListener for each checkbox and if the checkbox is clicked modify the preference value. I wrote a short explanation on how to use shared preferences with strings here: https://stackoverflow.com/a/9238997/1127492 To modify the example for boolean instead if string is straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM