Search code examples
androidbuttonsharedpreferencestogglebutton

Custom Toggle button with share preferences


I am trying to setup a custom toggle button where I use an Imagebutton and two different images to show which state is toggled. Right now I can toggle the picture listening for a click:

togglebtn = (ImageButton) findViewById(R.id.togglebtn);
        togglebtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                togglebtn.setImageResource(R.drawable.offbtn);
            }
        });

But I am not sure how to use sharepreferences save the state that the user selects. I want to use a boolean but all the shareprefences examples I find with booleans are all specific to check box not something like this.

How can I save the state of my toggle button?


Solution

  • try something like that (coded out of the head)

    editor = sharedPreferences.edit();
    
    boolean b = true; 
    editor.putBool("myBoolean", b);
    editor.commit();
    

    I would recommend you to save that onPause() of your activity and not onClick since I think it is expensive.