我已经使用FragmentPagerAdapter实现了TablLayout,我想添加或删除Tabs,但我不确定如何实现它。我已经搜索过这个但是找不到所有其他的例子都相似但不一样,因为我没有使用arraylist并且完全了解了这些教程。
这是FragmentPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Fragment tab1 = new Tab1Fragment();
return tab1;
case 1:
Tab2Fragment tab2 = new Tab2Fragment();
return tab2;
case 2:
Tab3Fragment tab3 = new Tab3Fragment();
return tab3;
case 3:
Tab4Fragment tab4 = new Tab4Fragment();
return tab4;
default:
return null;
}
}
@Override
public int getCount() {
return tabCount;
}
}
这是活动
public class TabLayoutDemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_demo);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1 Item").setIcon(android.R.drawable.ic_dialog_email));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2 Item").setIcon(android.R.drawable.ic_btn_speak_now));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3 Item").setIcon(android.R.drawable.ic_lock_idle_low_battery));
tabLayout.addTab(tabLayout.newTab().setText("Tab 4 Item").setIcon(android.R.drawable.ic_dialog_alert));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout
.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab_layout_demo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我正在使用支持TabLayout和Viewpager,据我所知,从适配器类中添加和删除选项卡,所以我尝试使用此代码,但我无法弄清楚tablItems这里指的是什么以及如何设置此变量或有没有其他方法来做到这一点?
public void removeTabPage(int position) {
if (!tabItems.isEmpty() && position<tabItems.size()) {
tabItems.remove(position);
notifyDataSetChanged();
}
}