首页 > 解决方案 > 如何减少 TabLayout 中的选项卡数量(每次都面临错误)

问题描述

我有一个带有 4 个选项卡的选项卡布局:

 private final String[] TITLE = {"NEAR BY", "GLOBAL", "ROOM", "PRIVATE"};

我不想要 TabLayout 中的“GLOBAL”选项卡,所以我从标题数组中删除了它,所以现在它看起来像这样:

  private final String[] TITLE = {"NEAR BY", "ROOM", "PRIVATE"};

但是,每次我再次运行该应用程序时,都会收到此错误:

引起:java.lang.ArrayIndexOutOfBoundsException: length=3; 索引=3

这是我的活动代码:

  public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        Log.i(TAG, "Create fragment position: " + position);
        switch (position) {
            case 0:
                return new NearbyFriendsFragment();
            case 1:
                GlobalFragment globalFragment = new GlobalFragment();
                setListener(globalFragment);
                return globalFragment;
            case 2:
                return new RoomFragment();
            default:
                return new PrivateFragment();
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Log.i(TAG, "Get page title: " + position);
        return TITLE[position];
    }
}
  @Override
public void onTabUpdate(int position, int countBadge) {
    Log.i(TAG, "On Tab update: " + position + " , Count Badge: " + countBadge);
    arrayCountBadge[position] = countBadge;
    customTabView(position, countBadge);
}

我是Android开发的初学者。

标签: androidarraysandroid-fragmentstabs

解决方案


您的 getCount 函数返回 4 而数组的大小仅为 3 尝试:

@Override
public int getCount() {
    return 3;
}

推荐阅读