【问题标题】:Dynamically replacing a fragment in ViewPager with TabsAdapter用 TabsAdapter 动态替换 ViewPager 中的片段
【发布时间】:2013-02-11 19:13:12
【问题描述】:

我将 ViewPager 与 ActionBar 选项卡结合使用,as illustrated here。我使用 ActionBarSherlock 是为了向后兼容,所以父活动扩展了 SherlockFragmentActivity,子片段扩展了 SherlockFragment。

该解决方案非常适合带有滑动的选项卡,但现在我想动态更改与其中一个选项卡关联的片段。

我已经阅读了许多 S.O.关于这个主题的答案(例如herehere),但我还没有找到关于如何在使用上面的 ViewPager + TabsAdapter 时动态更改片段的清晰说明。

这就是我现在所拥有的。当用户点击现有片段上的按钮时,我尝试替换父活动中的片段,如下所示:

AnotherFragment fragment = new AnotherFragment();           
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

int viewId = R.id.pager;                 // resource id of the ViewPager
int position = Constants.TAB_2;          // tab pos of the fragment to be changed

String tag = "android:switcher:" + viewId + ":" + position;

ft.replace(viewId, fragment, tag);
ft.commit();

mTabsAdapter.notifyDataSetChanged();

这不起作用,所以我错过了一些东西。我也尝试使用 getChildFragmentManager() 对嵌套片段执行此操作,但遇到了一个问题,因为没有 API 17,Android 4.2 就无法使用此函数。

感谢您的帮助!

【问题讨论】:

  • 看起来有一个错误是使用 ViewPager 的资源 ID R.id.pager。我将其切换为目标片段布局的 id,现在新片段可见。但是,它使旧片段在选项卡上仍然可见。这是朝着正确的方向前进,还是我需要尝试其他方法?
  • 更新:我升级到 API 17 (Android 4.2),所以我可以使用 getChildFragmentManager(),正如@georgiecasey 在回答stackoverflow.com/questions/7723964/… 时所推荐的那样。但是,仍然存在导致新旧片段同时在选项卡上可见的松散端。我将非常感谢任何显示如何在developer.android.com/reference/android/support/v4/view/… 中将嵌套片段与 Google TabsAdapter 一起使用的参考代码。谢谢。
  • 您也可以发布适配器代码吗?

标签: android android-fragments actionbarsherlock android-viewpager android-tabs


【解决方案1】:

我做了一个小例子,展示了类似的行为。我希望你可以重复使用它。

我认为关键是使用片段作为容器并使用它替换您的“真实”片段。

例如,看看如何导航到另一个片段:

        btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentTransaction trans = getFragmentManager()
                    .beginTransaction();
            /*
             * IMPORTANT: We use the "root frame" defined in
             * "root_fragment.xml" as the reference to replace fragment
             */
            trans.replace(R.id.root_frame, new SecondFragment());

            /*
             * IMPORTANT: The following lines allow us to add the fragment
             * to the stack and return to it later, by pressing back
             */
            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);

            trans.commit();
        }
    });

您可以在此处查看整个示例:

https://github.com/danilao/fragments-viewpager-example

【讨论】:

  • 请注意,link-only answers are discouraged,SO 答案应该是搜索解决方案的终点(相对于另一个参考中途停留,随着时间的推移往往会变得陈旧)。请考虑在此处添加独立的概要,并保留链接作为参考。
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多