SavedInstanceState总是空的片段 [英] SavedInstanceState is always null in fragment
问题描述
予有使用XML(和的setContentView()中活性)附连到的活性的片段。一有问题,因为我有我的片段非常动态的观点,所以,当方向变化 我必须恢复的看法所有状态。
我有问题,因为我使用这样的事情:
公共无效的onSaveInstanceState(包outState){
super.onSaveInstanceState(outState);
outState.putBoolean(恢复,真正的);
outState.putInt(nAndroids,2);
}
但方向变化后,当与参数捆绑savedInstanceState方法调用(如onCreateView等)我savedInstanceState总是空。
我不是在Android一个菜鸟,但是现在我因为这个问题很生气......
公共无效onViewCreated(查看视图,捆绑savedInstanceState){
super.onViewCreated(查看,savedInstanceState);
如果(savedInstanceState == NULL){
//未便
} 其他 {
// smthelse这是从来没有访问,因为包是总是空
}
。getListView()setDivider(getResources()getDrawable(R.drawable.list_divider));
}
所有的问题是,我不声明机器人:ID为XML中的片段。 Android的需要标识或标签来识别存储的片断并复制所有的元素在里面。所以,球员,记住 - 片段的每个实例都需要唯一的ID或者标签
!此外,当setRetainInstance(真)声明,然后捆绑应该总是返回null。
I have a fragment attached to the activity using XML (and setContentView() in activity). A have a problem because I have very dynamic views in my fragment, so when orientation changes I must restore all states of views.
I have problem because I'm using something like that:
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("restore", true);
outState.putInt("nAndroids", 2);
}
But after orientation change when methods with param Bundle savedInstanceState are called (like onCreateView etc) my savedInstanceState is always null.
I'm not a noob in the Android but now I'm very angry because of this problem...
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
//smth
} else {
// smthelse THIS IS NEVER REACHED BECAUSE BUNDLE IS ALWAYS NULL
}
getListView().setDivider(getResources().getDrawable(R.drawable.list_divider));
}
All the problem was in that I don't declare android:id for the fragment in XML. Android needs ID or TAG to recognize stored fragment and reproduce all elements in it. So guys, remember - every instance of fragment needs unique id or tag!
Also, when setRetainInstance(true) is declared then bundle should always return null.
这篇关于SavedInstanceState总是空的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!