5

我有带有查看寻呼机功能的 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) {

    }
}
4

1 回答 1

1

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

于 2012-08-15T18:25:40.600 回答