android – 按下后退按钮时保存状态
作者:互联网
我正在开发一个Android应用程序.如果我按下后退按钮应该保存我的应用程序的状态.我应该用什么来保存状态..am与所有这些onPause(),onResume()或onRestoresavedInstance()混淆???我应该使用哪些来保存我的应用程序状态?例如,当我按退出按钮时,我的整个应用程序应该退出我已经使用了finish()?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setOnClickListener(this);
LoadPreferences();
s1.setEnabled(false);
}
public void SavePreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", s1.isEnabled());
}
public void LoadPreferences()
{
System.out.println("LoadPrefe");
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
s1.setEnabled(state);
}
@Override
public void onBackPressed()
{
System.out.println("backbutton");
SavePreferences();
super.onBackPressed();
}
解决方法:
您需要做的是,而不是使用KeyCode Back,您已在Activity中覆盖以下方法,
@Override
public void onBackPressed() {
super.onBackPressed();
}
并使用SharedPrefrence保存Button的状态,下次当您输入Activity时,从Sharedpreference获取值并相应地设置按钮的启用状态.
例,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
@Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
标签:savestate,android,sharedpreferences,android-lifecycle 来源: https://codeday.me/bug/20190926/1819075.html