使用TabsAdapter动态替换ViewPager中的片段

时间:2013-02-11 19:13:12

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

我正在将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,此函数不可用。

感谢您的帮助!

1 个答案:

答案 0 :(得分: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

相关问题