我的应用程序存在一些问题...我有一个设置活动,用户可以为应用程序选择主题,然后我有一个显示“返回”的按钮,并将用户返回到主活动。之后,主题得到了保存,一切正常。但我的问题是,如果用户点击“Android后退按钮”,我的主题不会被保存。有办法解决它吗?
这是我的设置活动:
public class SettingsActivity extends Activity implements OnClickListener {
public static final String PREF_NAME = "MyPrefsFile";
public static int newTheme;
public final static int THEME_DARK = R.style.DarkTheme;
public final static int THEME_LIGHT = R.style.LightTheme;
public final static int THEME_COLORS = R.style.ColorsTheme;
public final static int THEME_PERF = R.style.Performance;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
newTheme = settings.getInt("themeCustom", 0);
if(newTheme == THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(newTheme == THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(newTheme == THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.Performance);
}
setContentView(R.layout.activity_settings);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
}
@Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor edit;
edit = settings.edit();
Intent intent = getIntent();
Intent main = new Intent(SettingsActivity.this,MainActivity.class);
switch (v.getId()) {
case R.id.button2:
newTheme = THEME_DARK;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button3:
newTheme = THEME_LIGHT;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button5:
newTheme = THEME_COLORS;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button6:
newTheme = THEME_PERF;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button4:
startActivity(main);
break;
default:
break;
}
}
}
非常感谢!! :)
答案 0 :(得分:2)
您可以使用onBackpressed()
public void OnBackpressed()
{
// do stuff ( same as what you did in your button click)
}
当活动检测到用户按下后退键时调用。默认实现只是完成当前活动,但您可以覆盖它以执行任何操作。
答案 1 :(得分:1)
你应该覆盖onBackPressed()方法
@Override
public void onBackPressed() {
super.onBackPressed();
// to do
}
答案 2 :(得分:0)
@Override
public void onBackPressed() {
//do whatever to save the settings
super.onBackPressed();
}
这样你就可以在按钮上做任何你想做的事情+它的初衷。
答案 3 :(得分:0)
您可以使用以下方式
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("themeCustom", newTheme);
editor.commit();
}