How to save (switch) button state in android?

2019-02-14 19:42发布

I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app. The code works fine while enabling and disabling switches. But i want to store the state of the switch. Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.

Every time when i close the application the switch state becomes disabled. Is there any way to store the switch State??

1条回答
在下西门庆
2楼-- · 2019-02-14 20:28

Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.

The following might help you:

@Override
public void onClick(View v) 
{
    if (toggle.isChecked()) 
    {
        SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
        editor.putBoolean("NameOfThingToSave", true);
        editor.commit();
    }
    else
    {
        SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
        editor.putBoolean("NameOfThingToSave", false);
        editor.commit();
    }
}

The final nail:

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
    toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}

Edit:

The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.

查看更多
登录 后发表回答