android - fragment 存储和重用 : Multiple Child fragments with TabView

标签 android android-fragments tabs fragment

你好,我被多个 fragment 存储和重用困住了。

  • 我的方案

我在 一个 Activity 中有 3 个选项卡(没有 viewpager 只是 fragment 更改),选项卡有 2-4 个子 fragment ,如下图所示。

所以,当我打开 Activity 时。
1) Tab1加载并显示F1 fragment 。
2) 点击Tab2 并显示F1 fragment 。
3) 点击 F1 中的按钮并移动到 Tab2 的 F2 fragment
4) 再次重复点击 F2 按钮并移动到 Tab2 的 F3 Fragment。
5) 现在我点击 Tab3 并打开 F1 fragment 。

这 5 个与 backstack null 配合得很好

fragmentTransaction.addToBackStack(null);

但要知道,

6) 当我点击 Tab2 时,它将始终显示 F1 fragment 。因为我在下面的代码 fragment 中管理 Activity 。

 switch (selected) {
        case 0:
            showFragment(TAB1.newInstance("", ""), TAG_HOME);
            break;
        case 1:
            showFragment(TAB2.newInstance("", ""), TAG_FAV);
            break;
        case 2:
            showFragment(TAB3.newInstance("", ""), TAG_ADD);
            break;
}
  • 我需要什么。

6) 我需要这样,假设我点击 Tab2 它显示 F3 Fragment becase 因为 last time 在这个 tab2 我是 打开 F3 fragment 。

那么如何处理 Store tab wise Fragment Backstrack。

是的还需要像下面的步骤(OnBackpress)

假设我在选项卡 2 F1 ->F2 ->F3
返回后按 F3 -> F2(backpress) -> F1(backpress) -> 关闭 Activity

enter image description here

最佳答案

您可以在 Hashmap 中存储 Stack of fragment 并在更改 tab 时检索。

 HashMap<String, Stack<Fragment>> mStacks = new HashMap<String, Stack<Fragment>>();
 mStacks.put(AppConstants.TAB_A, new Stack<Fragment>());
 mStacks.put(AppConstants.TAB_B, new Stack<Fragment>());
 mStacks.put(AppConstants.TAB_C, new Stack<Fragment>());

同时推送 fragment

 mStacks.get(tag).push(fragment);

同时弹出 fragment

 mStacks.get(mCurrentTab).pop();

用于工作演示 - Github

关于android - fragment 存储和重用 : Multiple Child fragments with TabView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992840/

相关文章:

android - NullPointerException 使用 AppCompat v21 在 Fragment 中获取 Google Map

android - Android 中的 Headless Fragment 和 Service 有什么区别?

vim - 是否可以在 VIM 中使用单独的缓冲区创建 2 个选项卡?

android - 自定义 ListView 错误 : java. lang.unsupportedoperationexception: addview

android - ViewPager 不显示任何内容 - android

python - 以 3 为一组打印 python 列表

Android 在 Fragment 中添加 Tab

android - 实现 Parcelable 接口(interface)时如何读/写 bool 值?

android - 在 Android Studio 中找不到 opencv2

c# - PorterDuff.Mode.Multiply 没有按预期工作?黑色背景而不是透明