vendredi 19 août 2016

Shared Preference saving the checkbox action

I was able to store the value of checkbox using shared preference but I was not able to save the action its meant to do.The action what i need is when checkbox is checked a button should display,if checkbox is unchecked button should not display(hiding/showing button is done in different activity). So what I did was i passed the value isCheckedValue = isChecked; under if/else condition

final CheckBox checkBox = (CheckBox) findViewById(R.id.add_fb);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();

if(preferences.contains("checked") && preferences.getBoolean("checked",false) == true) {
    checkBox.setChecked(true);
} else {
    checkBox.setChecked(false);
}

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        editor.putBoolean("checked", true);
        editor.apply();

        if(checkBox.isChecked()) {
            isCheckedValue = isChecked;
            editor.putBoolean("checked", true);
            editor.apply();
        }else{
            editor.putBoolean("checked", false);
            editor.apply();
        }
    }
});

if chkbox is checked the value will pass using intent in onBubbleClick using the boolean passing data in.putExtra("yourBoolName", isCheckedValue ); you could notice it in below bunch of code

private void addNewBubble() {
    BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
    bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
        @Override
        public void onBubbleRemoved(BubbleLayout bubble) {
            finish();
            System.exit(0);
        }
    });
    bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {

        @Override
        public void onBubbleClick(BubbleLayout bubble) {
            Intent in = new Intent(MainActivity.this, PopUpWindow.class);
            in.putExtra("yourBoolName", isCheckedValue );
            startActivity(in);

        }
    });
    bubbleView.setShouldStickToWall(true);
    bubblesManager.addBubble(bubbleView, 60, 20);
}

How it works: At the very beginning the button is not displayed until the checkbox is clicked, the button gets displayed once the checkbox is checked and never gets hidden even after unchecked the checkbox.
How it's meant to work The button should display if the checkbox is checked and button should hide if the checkbox is unchecked.




Aucun commentaire:

Enregistrer un commentaire