【问题标题】:How to keep the content of a ListView even after changing Fragment through the Drawer即使通过 Drawer 更改 Fragment 后如何保留 ListView 的内容
【发布时间】:2014-09-25 11:03:47
【问题描述】:

我正在使用 Android Studio,并创建了一个包含 NavigationDrawerFragment 的 Activity。 其中一个片段是使用带有复杂项目的自定义 ArrayAdapter 在 ListView 中加载 SQLite 数据库的内容。

我的问题是,如果我在抽屉中选择另一个片段,然后回到这个片段,再次调用Fragment的onCreate(),onCreateView()也是如此,再次加载数据库。

如何在无需加载数据库或再次填充列表的情况下保留所有内容?

方向改变时我没有这个问题,所以我有点困惑。也许是因为我有纵向和横向的布局?

这里是 onCreateView() 的代码

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    getActivity().getActionBar().show();
    View view = inflater.inflate(R.layout.fragment_papers, container, false);

        allItems = new ArrayList<ItemData>();

            getAllItemsFromDB("");


        mAdapter = new ItemsList(getActivity(), allItems, this, mDBApi);

        // Set the adapter

        mListView = (AbsListView) view.findViewById(R.id.list);

        mListView.setAdapter(mAdapter);


        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);

    return view;
}

getAllItemsFromDB() 包含类似

public void getAllItemsFromDB(String query){

Cursor c = sqldb.rawQuery("SELECT * FROM 'Table' " + query, null);

    while (c.moveToNext()) {

        allItems.add(parseSQL(sqldb, c));


    }

    c.close();

}

【问题讨论】:

  • 你知道了吗@Myoch

标签: android sqlite listview android-fragments


【解决方案1】:

设置你的数组列表静态

private static List<ItemData> allItems;

然后检查它是否为空并只初始化一次

if(allItems == null) {
     allItems = new ArrayList<ItemData>();
     getAllItemsFromDB("");
}

【讨论】:

  • 如果内容随用户操作而变化,是否可以将其设为静态?
【解决方案2】:

可能是你每次都加载帧

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, new UrFragment()).commit();

不要那样做,创建片段实例并使用它。

    // update the main content by replacing fragments
    Fragment fragment = new UrFragment();
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

【讨论】:

  • 我已经在使用第二个选项了。我已经检查过了,新的 Fragment() 调用位于 NavigationDrawer 的 onCreateView() 方法中。而且这个方法只在应用启动时调用一次。
  • 在设置 -> 开发者选项中启用了不保留活动选项。
  • 什么是设置 -> 开发者选项?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多