3

我将 ViewPager 与 ActionBar 选项卡结合使用,如此处所示。我使用 ActionBarSherlock 是为了向后兼容,因此父活动扩展了 SherlockFragmentActivity,子片段扩展了 SherlockFragment。

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

我已经阅读了关于这个主题的大量 SO 答案(例如这里这里),但是我没有找到关于如何在使用上面的 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 就无法使用此函数。

谢谢你的帮助!

4

1 回答 1

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

于 2014-01-30T10:09:02.703 回答