简体   繁体   中英

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?

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.

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.

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