[英]IndexOutOfBoundsException when selecting tab in Tablayout
I get IndexOutOfBoundsException
error when i want selecting the tab in the TabLayout
: This is the initTablayout function , that called in the onCreate
method: 当我想在
TabLayout
选择选项卡时,我得到IndexOutOfBoundsException
错误:这是在onCreate
方法中调用的initTablayout函数:
//======================================== Init Tablayout and view pager
private void initTabLayout() {
mainActivityViewPager = (ViewPager) findViewById(R.id.view_pager_main_activity);
mainActivityTabLayout = (TabLayout)findViewById(R.id.tab_layout_main_activity);
TabLayout.Tab tab = mainActivityTabLayout.getTabAt(1);
tab.select();
FragmentManager manager = getSupportFragmentManager();
MainActivityPagerAdapter adapter = new MainActivityPagerAdapter(manager);
mainActivityViewPager.setAdapter(adapter);
mainActivityTabLayout.setupWithViewPager(mainActivityViewPager);
mainActivityViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mainActivityTabLayout));
mainActivityTabLayout.setTabsFromPagerAdapter(adapter);
}
I got this error where i choose index of selected tab on the getTabAt(1)
method , i have three tab on the PagerAdapter
class : 我得到了这个错误,我在
getTabAt(1)
方法中选择了选定选项卡的索引,我在PagerAdapter
类上有三个选项卡:
public class MainActivityPagerAdapter extends FragmentStatePagerAdapter {
//============================================ Constructor
public MainActivityPagerAdapter(FragmentManager fm) {
super(fm);
}
//============================================ GetItem Method ()
@Override
public Fragment getItem(int position) {
Fragment frag = null;
switch (position) {
case 0:
frag = new Fragment_one();
break;
case 1:
frag = new Fragment_two();
break;
case 2:
frag = new Fragment_three();
break;
}
return frag;
}
//============================================= GetCount Method ()
@Override
public int getCount() {
return 3;
}
//============================================= GetPageTitle
@Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "اول ";
break;
case 1:
title = "دوم ";
break;
case 2:
title = "سوم ";
break;
}
return title;
}
}
Complete error is : 完整错误是:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
It seem like you forget to addTab to your mainActivityTabLayout
so your TabLayout
will have 0 item. 看起来你忘了添加toTab到你的
mainActivityTabLayout
所以你的TabLayout
将有0项。 Therefore, you got IndexOutOfBoundsException
when you access to tab1 因此,访问tab1时会出现
IndexOutOfBoundsException
mainActivityTabLayout.addTab(tabLayout.newTab().setText("1"));
mainActivityTabLayout.addTab(tabLayout.newTab().setText("2"));
mainActivityTabLayout.addTab(tabLayout.newTab().setText("3"));
Select tab3 选择tab3
Do following : 做以下事项:
mainActivityTabLayout.addTab(tabLayout.newTab().setText("3"),true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.