SAW*_*UNG 4 android fragment android-fragments
在我的项目中,我使用名为PassengerInformation.java的片段.在该片段中,我使用onSaveInstanceState和onCreate方法.在onCreate方法中,如果没有从onSaveInstanceState传递的包,我应该清除sharedPreferences,如果onSaveInstanceState传递一个bundle,我就不需要清除sharedPreferences.我的问题是当我按下时,onSaveInstanceState没有被调用我应该记录它但是日志不打印任何东西.
谢谢
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//clear sharedpreferences PassengerInformation is firsttime loaded
if( savedInstanceState == null ) {
Log.i("clear PassengerInformation", "sharedPreferences clear");
edit.clear().commit();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putBoolean("clearPreferences", false);
Log.i("saveInstanceState PassengerInformation", "save");
}
Run Code Online (Sandbox Code Playgroud)
通常,当您将方向从纵向更改为横向时,将调用保存实例状态.
例如:您正在显示结果,如果用户更改方向,您需要显示相同的结果,
onresume - > SavedinstanceState(您将使用键和值来存储数据) - > destroy
和onCreate-> Restore savedInstanceState(您将使用键的方法getExtra(),并显示存储在restoreSavedInstance状态的结果.
你可以从中读到一个很好的解释
例如:public static final String key ="Hello";
// you can get the data here.
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getString(key);
Toast.makeText(this, "Restore state"+ savedInstanceState.getString(key), Toast.LENGTH_SHORT)
.show();
text.setText(key); // here the output will be Good morning.
}
// orientation change where from on resume-> destroy state, if you need to handle any saved data
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Toast.makeText(this, "saved state", Toast.LENGTH_SHORT)
.show();
outState.putString(key, "Good morning");
}
Run Code Online (Sandbox Code Playgroud)
onSaveInstanceState()当用户按 BACK 时不应调用。
原因:
如果您在 Activity 中并点击设备上的“后退”按钮,则您的 Activity 将完成(),下次您启动应用程序时,它会再次启动(听起来像是重新创建的,不是吗?),但这次没有已保存状态,因为当您点击“后退”按钮时有意退出它。
当用户更改配置(例如,旋转屏幕)时,如果 Android 认为 Activity 有被破坏的风险,但仍可在堆栈上访问,或者可能还有其他一些情况,它将被调用。
Android 中点击后退按钮时读取onSaveInstanceState
| 归档时间: |
|
| 查看次数: |
3425 次 |
| 最近记录: |