我有一个简单的场景,MainActivity的Launch按钮启动第二个Activity。在第二个Activity中,我根据用户点击动态添加视图,但是当我返回主Activity并返回第二个活动时,添加的视图不会保存。我发现只要按下主页按钮并调用onSaveInstanceState,当我进入活动时它就会被恢复,但是当我去MainActivity时,onSaveInstanceState没有被调用,视图就消失了。
所以我希望能够知道当活动进入后台隐藏状态时如何调用onSaveInstanceState()。或者关于如何保存ViewGroup的任何其他想法
public class CountActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter_activity);
container = (LinearLayout) findViewById(R.id.counterContainer);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Log.d("TAG","CountActivity onCreate");
}
public void AddCounter(View view) {
View parent = (View) view.getParent();
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addedView = layoutInflater.inflate(R.layout.fragment_counter, null);
container.addView(addedView);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d("TAG", "CountActivity onSaveInstanceState");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("TAG", "CountActivity onRestoreInstanceState");
}
@Override
protected void onPause() {
Log.d("TAG", "CountActivity onPause");
super.onPause();
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("TAG", "CountActivity onRestart");
}
@Override
protected void onResume() {
super.onResume();
Log.d("TAG", "CountActivity onResume");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("TAG", "CountActivity onDestroy");
}
@Override
protected void onStop() {
super.onStop();
Log.d("TAG", "CountActivity onDestroy");
}
@Override
protected void onStart() {
super.onStart();
Log.d("TAG", "CountActivity onStart");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d("TAG", "CountActivity onConfigurationChanged");
}
}