Android为FragmentPagerAdapter添加和删除片段

时间:2016-09-27 14:12:24

标签: java android android-fragments fragmentpageradapter

我有一个标签布局和一个视图寻呼机。选项卡布局始终以单个选项卡开头,但是,我希望能够通过按钮动态添加和删除新选项卡。

on onCreate:

mViewPager  = (ViewPager)   view.findViewById(R.id.viewpager);
mToolbar    = (Toolbar)     view.findViewById(R.id.toolbar);
mTabLayout  = (TabLayout)   view.findViewById(R.id.tabs);

setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);

setupViewPager方法:

private void setupViewPager(ViewPager viewPager) {
    mAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
    mAdapter.addFragment(new CycleFragment(), "TEST TAB");
    viewPager.setAdapter(mAdapter);
}

viewPageAdapter类:

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

是否可以向viewpager动态添加和删除片段?我通过这种方法理解,添加新片段相对简单。但是,我该如何删除碎片?

1 个答案:

答案 0 :(得分:0)

public void removeFragment(Fragment fragment, String title) {
    mFragmentList.remove(fragment);
    mFragmentTitleList.remove(title);
    notifyDataSetChanged(); 
}