有没有办法动态隐藏并在android.support.design.widget.TabLayout
例如,单击活动中的其他位置的按钮/视图,隐藏或显示位置3中的选项卡或显示/隐藏特定ID的选项卡。
我尝试删除标签tabLayout.removeTabAt(3);
并重新添加,但在滑动标签时出现异常,因为轻扫仍然会尝试转到已删除的标签
12-08 12:30:42.904 29052-29052/com.example.p1v1 E/MessageQueue-JNI﹕ java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
我有以下代码:
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
...
...
public class BaseTabActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_w,
R.drawable.ic_x,
R.drawable.ic_y,
R.drawable.z
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_tab);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
...
...
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FeedFragment(), "W");
adapter.addFragment(new FeedFragment(), "X");
adapter.addFragment(new FeedFragment(), "Y");
adapter.addFragment(new FeedFragment(), "Z");
viewPager.setAdapter(adapter);
}
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); //replace below with this if you want tab text and not just icons
// return null to display only the icon
return null;
}
}
}