在ActionBar选项卡中使用ViewPager替换片段

时间:2012-07-13 12:21:11

标签: android android-fragments android-actionbar android-viewpager

我有带有查看寻呼机功能的ActionBar标签。我的问题是在这些标签中,我无法替换碎片。我使用下面的代码替换片段,但它没有替换,主要片段仍然存在。此外,在其他标签中也存在第二个片段。我的TabListener也低于片段的替换。

private void addFragment(Fragment fragment, boolean addToBackStack, int transition)
{
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.details_container, fragment);
    fragmentTransaction.setTransition(transition);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

public static class TabsAdapter extends FragmentPagerAdapter
        implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
    private final Context mContext;
    private final ActionBar mBar;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    static final class TabInfo {
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(Class<?> _class, Bundle _args) {
            clss = _class;
            args = _args;
        }
    }

    public TabsAdapter(FragmentActivity activity, ActionBar bar, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mBar = bar;
        mViewPager = pager;
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(ActionBar.Tab tab, Class<? extends Fragment> clss, Bundle args) {
        TabInfo info = new TabInfo(clss, args);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        mBar.addTab(tab);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    @Override
    public Fragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        mBar.setSelectedNavigationItem(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        Object tag = tab.getTag();
        for (int i=0; i<mTabs.size(); i++) {
            if (mTabs.get(i) == tag) {
                mViewPager.setCurrentItem(i);
            }
        }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {

    }
}

1 个答案:

答案 0 :(得分:1)

我建议您查看整个Replace Fragment inside a ViewPager主题并查看https://stackoverflow.com/a/11974777/685292中的示例。