Android - 删除Tab和TabFragment

时间:2016-09-14 13:11:53

标签: android android-tablayout

这是活动onCreate

final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("A"));
tabLayout.addTab(tabLayout.newTab().setText("B"));
tabLayout.addTab(tabLayout.newTab().setText("C"));

final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
TabFragmentPagerAdapter adapter = new TabFragmentPagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);

适配器

public class TabFragmentPagerAdapter extends FragmentStatePagerAdapter {

  private int numberOfTabs;

  public TabFragmentPagerAdapter(FragmentManager fm, int numberOfTabs) {
    super(fm);
    this.numberOfTabs = numberOfTabs;
  }

  @Override
  public Fragment getItem(int position) {
    switch (position) {
        case 0:
            FragmentA a = new FragmentA();        
            return a;
        case 1:
            FragmentB b = new FragmentB();
            return b;
        case 2:
            FragmentA c = new FragmentC();
            return c;
        default:
            return null;
    }
  }

  @Override
  public int getCount() {
    return numberOfTabs;

  }
}

我可以使用tabLayout.removeTabAt(1)删除标签,但如何删除位置1的片段?

2 个答案:

答案 0 :(得分:0)

您还需要从适配器中删除页面。

尝试以下代码:

public void removeTab(int position) {
    if (mTabLayout.getTabCount() >= 1 && position<mTabLayout.getTabCount()) {
      mTabLayout.removeTabAt(position);
      mPagerAdapter.removeTabPage(position);
    }
}

//This code will go in the adapter
public void removeTabPage(int position) {
      numberOfTabs = numberOfTabs - 1;
      notifyDataSetChanged();
}

notifyDataSetChanged();告诉适配器我们删除该项非常重要。

答案 1 :(得分:0)

唯一有效的灵魂就是在每个标签中添加片段数组列表,并动态删除标签和片段。

private ArrayList<Fragment> fragments;

@Override
    public Fragment getItem(int position) {
        if (position == 0)
            return fragments.get(position);
        if (position == 1)
            return fragments.get(position);
        if (position == 2)
            return fragments.get(position);
        return null;
    }

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


    public void removeTabPage(int position) {
        if (!fragments.isEmpty() && position<fragments.size()) {
            fragments.remove(position);
            notifyDataSetChanged();
        }
    }