这是一个情况。我想从片段 A-> B-> C 导航。
B Fragment中有listview。在项目上单击我打开详细视图 C 片段。
当然,我使用了替换方法并在从 B 到 C 的事务处理时添加了 addtoBackStack(null) ,以便在按“返回”时它返回到 B。
一切顺利。但是当我从 C 返回 B 时,视图正在刷新,因此 Web 服务被再次调用。我不想这样做。我想用listview保留B Fragment状态。
我收到了一些保留实例的帖子,但没有多大帮助。
任何帮助深表感谢。
Thanks.
正如所解释的here http://www.vogella.com/articles/AndroidFragments/article.html#usingfragments_您可以使用 onSaveInstanceState() 将数据保存在 Bundle 中,并在 onRestoreInstanceState() 方法中检索该数据。
通常 setRetainState(true) 被提及作为将 ui 状态保持在片段中的方法,但它对您不起作用,因为您正在使用后堆栈。
因此,一个好方法可能是在 onSaveInstanceState() 中保存滚动位置并在 onRestoreInstanceState() 中恢复它,如下所示:
public class MyListFragment extends ListFragment {
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int index = this.getListView().getFirstVisiblePosition();
View v = this.getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt("index", index);
outState.putInt("top", top);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
[...]
if (savedInstanceState != null) {
// Restore last state for checked position.
index = savedInstanceState.getInt("index", -1);
top = savedInstanceState.getInt("top", 0);
}
if(index!=-1){
this.getListView().setSelectionFromTop(index, top);
}
}
此外,您还可以找到更详细的类似示例here http://developer.android.com/guide/components/fragments.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)