android - 避免在 fragment 中重新加载

标签 android gridview android-fragments slidingmenu

我正在制作一个汽车查找应用程序。我在 gridview 中显示结果,并且在右侧还有一个滑动菜单(用于搜索过滤器)。我在 fragment 的帮助下制作了整个应用程序。在 gridview 我在底部加载更多页脚,当我点击第 12 个位置 gridview 时,我正在开始另一个这样的 fragment :

SearchDetailActivity.goToFragment(ProductDetailFragment.newInstance(map,position));

在 ProductDetailFragment 中我有一个后退按钮,可以像这样返回到上一个 fragment :

SearchDetailActivity.goToFragment(SearchDetailFragment.newInstance(str_url));

现在当我再次回来时,数据显示从第​​ 0 到第 10 项。

在 goToFragment() 中我写了这段代码:

public static void goToFragment(Fragment fragment) {
    Log.d("GoToFrag","sjdk>>"+fragment);
    Fragment tmp = fm.findFragmentByTag(fragment.getClass().getName());
    if (tmp != null && tmp.isVisible())
        return;

    ft = fm.beginTransaction();
    ft.replace(R.id.main_fragment, fragment, fragment.getClass().getName());
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.commit();
    currentTag = fragment.getClass().getName();
}

我想避免从 ProductDetailFragment 返回时重新加载数据。如果我使用 Activity,那么我可以使用 onBackPressed() 来返回并避免重新加载,但是在 Fragment 中,当我按下应用程序的后退按钮时,它会重新加载 SearchDetatilFragment,这非常烦人..请帮助我..提前致谢。

最佳答案

大约 3 个月以来,我一直在偶然发现这个问题。终于我的努力得到了返回,找到了解决方案。

问题是,当您使用“替换”时,这等同于“删除和添加”。 所以当按下后退按钮时, fragment 被完全删除并重新创建。 相反,我们必须隐藏父 fragment 并显示子 fragment 。

调用serach fragment 的地方

 ft = fm.beginTransaction();
 ft.replace(R.id.main_fragment, yourSearchFragment, "searchFragment");
 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
 ft.commit();

调用productDetails fragment 时

 ft = fm.beginTransaction();
 ft.hide(getFragmentManager().findFragmentByTag("searchFragment"));
 ft.add(R.id.main_fragment, yourDetailfragment);
 ft.addToBackStack(null);
 ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
 ft.commit();

祝你好运

关于android - 避免在 fragment 中重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758344/

相关文章:

android - Fragment 中的 View 为空

android - android studio 更新后 ADB 不工作

Android studio 3.5重构问题

asp.net - 如何基于DataKey在ASP.NET GridView中设置选定的行?

c# - 如何像 Repeater 一样运行 GridView?

android - 单击 View 寻呼机第二个 fragment 中的按钮时返回 View 寻呼机的第一个 fragment

android - Here Maps - 在 TabLayout 的 fragment 中使用 MapFragment

java - 使用 Eclipse 在多台计算机上开发 Android 应用程序

android - 数据绑定(bind) : How pass Context in xml to method?

asp.net - 将字典绑定(bind)到 GridView