我的应用程序中有简单的ActionBar,右侧有图标,当用户点击该图标时,我想将布尔变量存储为设置为真的Sharedpreference变量并更改ActionBar的菜单,当用户如果获取Sharedpreference的值为true,则再次启动应用程序,然后加载ActionBar菜单(R.menu.main),否则加载ActionBar菜单(R.menu.menu2)。
这是onCreate函数中的代码。
preferences = getSharedPreferences(SharedPreferenceChecking, MODE_PRIVATE);
if(preferences.getBoolean(KEY_VALUE, false) == false){
checkingMenu = false;
editor = getSharedPreferences(SharedPreferenceChecking, MODE_PRIVATE).edit();
editor.putBoolean(KEY_VALUE, checkingMenu);
editor.apply();
} else{
checkingMenu = true;
editor = getSharedPreferences(SharedPreferenceChecking, MODE_PRIVATE).edit();
editor.putBoolean(KEY_VALUE, checkingMenu);
editor.apply();
}
以下是加载菜单状态的代码
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
preferences = getSharedPreferences(
SharedPreferenceChecking, MODE_PRIVATE);
Boolean check = preferences.getBoolean(KEY_VALUE, false);
if (check == false) {
getMenuInflater().inflate(R.menu.menu2, menu);
} else if (check == true) {
getMenuInflater().inflate(R.menu.main, menu);
}
return true;
}
这是onOptionsItemSelected
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
preferences = getSharedPreferences(
SharedPreferenceChecking, MODE_PRIVATE
);
//noinspection SimplifiableIfStatement
if (id == R.id.action_change1) {
Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
checkingMenu = preferences.getBoolean(KEY_VALUE, false);
editor.putBoolean(KEY_VALUE, checkingMenu);
editor.apply();
return true;
} else if (id == R.id.action_change2) {
Toast.makeText(this, "False", Toast.LENGTH_SHORT).show();
checkingMenu = preferences.getBoolean(KEY_VALUE, true);
checkingMenu = true;
editor.putBoolean(KEY_VALUE, checkingMenu);
editor.apply();
return true;
}
return super.onOptionsItemSelected(item);
}