2016-09-14 53 views
0

這是活動的onCreateAndroid的 - 刪除選項卡和TabFragment

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刪除片段?

回答

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();這是非常重要的是告訴我們的適配器中刪除該項目。

+0

什麼是tabItems? – Coder

+0

其你arraylist –

+0

我沒有一個。 Arraylist的? – Coder

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(); 
     } 
    }