我见过其他类似的问题,但没有一个问题在努力!我有一个切换按钮。即使关闭/重新打开应用程序,我也希望保存ToggleButton的状态(选中true或false)。
我的代码如下所示,但不会运行
公共类MainActivity扩展了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));
}};
感谢您的帮助!
答案 0 :(得分:2)
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
应该是INSIDE onCreate()
,将其作为最后一个声明。
此外,它更容易使用
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
答案 1 :(得分:1)
好的,我有答案供将来参考。我原来的尝试没有正确使用共享首选项。您必须为共享首选项对象创建“密钥”和“名称”。然后在代码中调用它,如下所示:
公共类MainActivity扩展了AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}