如何保存为列表视图片段的状态 [英] How to save state of Fragment having listview

查看:132
本文介绍了如何保存为列表视图片段的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种情况。我想从片段A-导航> B->℃。

Here is a situation. I want to navigate from Fragment A-> B-> C.

输入B片段有列表视图。在项目点击我打开详细视图C语言程序段。 Ofcourse我用替换法,并添加addtoBackStack(空),而选自B transactiong到C,这样就回到preSS它返回到B。

In B Fragment there is listview. On item click I open the detail view C Fragment. Ofcourse I used replace method and added addtoBackStack(null) while transactiong from B to C so that on Back press it returned to B.

一切顺利。但是,当我返回到B从C,该视图被刷新,因此Web服务被再次调用。我不想这样做。我想保留对B片段状态列表视图。

All goes well. But when I return to B from C, the view is being refreshed and hence the webservice is being called again. I don't want to do this. I want to retain the B Fragment state with listview.

我得到了保留实例的一些职位,但它并没有帮助那么多。

I got some post of Retain Instance, but it didn't help that much.

任何帮助是非常AP preciated。

Any help is much appreciated.

感谢。

推荐答案

由于这里解释你可以使用的onSaveInstanceState(),以将数据保存在捆绑和检索的onRestoreInstanceState()方法的数据。

As explained here you can use onSaveInstanceState() to save data in the Bundle and retrieve that data in the onRestoreInstanceState() method.

通常setRetainState(真)被提及的方式保持在片段中的UI状态,但对于你,因为你正在使用的backstack这是行不通的。

Often setRetainState(true) is mentioned as way to keep the ui state in fragment, but it does not work for you because you are using the backstack.

因此​​,对于你的好方法可能是保存的onSaveInstanceState(中的scrollPosition),并恢复它在onRestoreInstanceState()是这样的:

So a good way for you could be to save the scrollposition in onSaveInstanceState() and restore it in onRestoreInstanceState() like this:

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);
  }

}

更进一步,你可以在这里找到更详细的similiar例如

Further more you can find a more detailed similiar example here.

这篇关于如何保存为列表视图片段的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆