Android – how do I save the status of the toglebutton on / off selection?

Hello, I have implemented the application based on the togglebutton selection. But when I close the application and reopen it, it will enter its default selection of "close". Then any bug can tell me how to save the selected state of the togglebutton and perform some operations according to the selected state of the togglebutton.. thank you

resolvent:

Use SharedPreferences

tg = (ToggleButton) findViewById(R.id.toggleButton1);

tg.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {

    if((tg.isChecked()))
        {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("tgpref", true); // value to store
                editor.commit();
        }
        else
        {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("tgpref", false); // value to store
                editor.commit();
        }
    }
});

This is how to retrieve values:

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true);  //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
  tg.setChecked(true);
}
else
{
  tg.setChecked(false);
}

I didn't verify this code, but it's easy to take a look at some examples on the Internet!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>