0

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.

My code looks like this below, but it will not run

public class MainActivity extends AppCompatActivity {

    ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
    SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
    editor.putBoolean("toggleState1", toggle1.isChecked());
    editor.commit();
}

private void loadPreference (Context context)
{
    SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
    toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};

Thanks for the help!

4

2 に答える 2

2
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);

INSIDEonCreate()にする必要があります。これを最後のステートメントにします。

また、さらに使いやすく

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
于 2016-05-05T20:22:48.853 に答える