Nick
Nick

Reputation: 9373

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?

Upvotes: 0

Views: 717

Answers (2)

Budius
Budius

Reputation: 39846

further from @Anthea comment regarding the preferences, you shouldn't be using the ImageButton.

There are ToggleButton, CheckBox and Switch for boolean options implementation. You should check them. You also shouldn't be programmatically changing the drawable. You can/should set a selector drawable XML with the pressed and not pressed and set them on the layout.

Upvotes: 0

Anthea
Anthea

Reputation: 3809

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.

Upvotes: 1

Related Questions