如何在Android的TabLayout中以编程方式添加选项卡

18

在我的应用程序中,我想要在TabLayout中动态创建标签页,并且当从服务器获取到的数据数量 > 0时,创建标签页
我使用这个库来实现TabLayout:https://github.com/egemenmede/etiyabadgetab

为了完成这项工作,我编写了以下代码:

        FullSearchSendData sendData = new FullSearchSendData();
    sendData.setKey(fullSearchText);
    sendData.setLoadImages(true);
    sendData.setSearchInCelebrities(true);
    sendData.setSearchInMovies(true);
    sendData.setSearchInSeries(true);
    sendData.setSearchInEpisodes(true);
    sendData.setSearchInUsers(true);
    sendData.setPageIndex(1);
    sendData.setPageSize(10);
    sendData.setMaxDistance(1);

    fullSearch_LoadLay.setVisibility(View.VISIBLE);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<FullSearchResponse> call = api.getFullSearch(sendData);

    call.enqueue(new Callback<FullSearchResponse>() {
        @Override
        public void onResponse(Call<FullSearchResponse> call, Response<FullSearchResponse> response) {
            FullSearchResponse searchResponse = response.body();
            if (searchResponse.getData().getCelebritiesCount() > 0) {
                celebritiesCount = searchResponse.getData().getCelebritiesCount();
                celebrityList.clear();
                celebrityList.addAll(searchResponse.getData().getCelebrities());
            }
            if (searchResponse.getData().getMoviesCount() > 0) {
                movieCount = searchResponse.getData().getMoviesCount();
                movieList.clear();
                movieList.addAll(searchResponse.getData().getMovies());
            }
            if (searchResponse.getData().getSeriesCount() > 0) {
                serieCount = searchResponse.getData().getSeriesCount();
                seriesList.clear();
                seriesList.addAll(searchResponse.getData().getSeries());
            }
            if (searchResponse.getData().getUsersCount() > 0) {
                usersCount = searchResponse.getData().getUsersCount();
                userList.clear();
                userList.addAll(searchResponse.getData().getUsers());
            }

            setupViewPager(fullSearch_ViewPager);
            setupTabs();

            fullSearch_LoadLay.setVisibility(View.GONE);

            //fullSearch_Swipe.setRefreshing(false);
        }

        @Override
        public void onFailure(Call<FullSearchResponse> call, Throwable t) {
            fullSearch_LoadLay.setVisibility(View.GONE);
            fullSearch_ReloadLay.setVisibility(View.VISIBLE);
        }
    });
}

private void setupTabs() {
    if (celebritiesCount > 0) {
        fullSearch_tabLayout.addTab(new TabLayout(context).newTab());
        fullSearch_tabLayout.selectEtiyaBadgeTab(0)
                .tabTitle("Celebrities")
                .tabTitleColor(R.color.white)
                .tabBadge(true)
                .tabBadgeCount(celebritiesCount)
                .tabBadgeCountMore(false)
                .tabBadgeBgColor(R.color.colorAccent)
                .tabBadgeTextColor(R.color.white)
                .tabBadgeStroke(2, R.color.white)
                .tabBadgeCornerRadius(15)
                .createEtiyaBadgeTab();
    }
    if (movieCount > 0) {
        fullSearch_tabLayout.addTab(new TabLayout(context).newTab());
        fullSearch_tabLayout.selectEtiyaBadgeTab(1)
                .tabTitle("Movies")
                .tabTitleColor(R.color.white)
                .tabBadge(true)
                .tabBadgeCount(movieCount)
                .tabBadgeCountMore(false)
                .tabBadgeBgColor(R.color.colorAccent)
                .tabBadgeTextColor(R.color.white)
                .tabBadgeStroke(2, R.color.white)
                .tabBadgeCornerRadius(15)
                .createEtiyaBadgeTab();
    }
    if (serieCount > 0) {
        fullSearch_tabLayout.addTab(new TabLayout(context).newTab());
        fullSearch_tabLayout.selectEtiyaBadgeTab(2)
                .tabTitle("Series")
                .tabTitleColor(R.color.white)
                .tabBadge(true)
                .tabBadgeCount(serieCount)
                .tabBadgeCountMore(false)
                .tabBadgeBgColor(R.color.colorAccent)
                .tabBadgeTextColor(R.color.white)
                .tabBadgeStroke(2, R.color.white)
                .tabBadgeCornerRadius(15)
                .createEtiyaBadgeTab();
    }
    if (usersCount > 0) {
        fullSearch_tabLayout.addTab(new TabLayout(context).newTab());
        fullSearch_tabLayout.selectEtiyaBadgeTab(3)
                .tabTitle("Users")
                .tabTitleColor(R.color.white)
                .tabBadge(true)
                .tabBadgeCount(usersCount)
                .tabBadgeCountMore(false)
                .tabBadgeBgColor(R.color.colorAccent)
                .tabBadgeTextColor(R.color.white)
                .tabBadgeStroke(2, R.color.white)
                .tabBadgeCornerRadius(15)
                .createEtiyaBadgeTab();
    }
}

private void setupViewPager(ViewPager viewPager) {

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    if (celebritiesCount > 0) {
        adapter.addFrag(FullSearchCelebritiesFragment.getInstance(celebrityList, celebritiesCount, fullSearchText), "Celebrities");
    }
    if (movieCount > 0) {
        adapter.addFrag(FullSearchMovieFragment.getInstance(movieList, movieCount, fullSearchText), "Movies");
    }
    if (serieCount > 0) {
        adapter.addFrag(FullSearchSeriesFragment.getInstance(seriesList, serieCount, fullSearchText), "Series");
    }
    if (usersCount > 0) {
        adapter.addFrag(FullSearchUsersFragment.getInstance(userList, usersCount, fullSearchText), "Users");
    }
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

但是当我运行应用程序时,出现了以下错误:
Process: com.test.example, PID: 3804
                                                                   java.lang.IllegalArgumentException: Tab belongs to a different TabLayout.
                                                                       at android.support.design.widget.TabLayout.addTab(TabLayout.java:476)
                                                                       at android.support.design.widget.TabLayout.addTab(TabLayout.java:464)
                                                                       at android.support.design.widget.TabLayout.addTab(TabLayout.java:443)
                                                                       at com.test.example.Activities.FullSearch.setupTabs(FullSearch.java:173)
                                                                       at com.test.example.Activities.FullSearch.access$900(FullSearch.java:44)
                                                                       at com.test.example.Activities.FullSearch$1.onResponse(FullSearch.java:156)
                                                                       at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5349)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

当点击错误信息中的第一个链接时,转到此代码:
fullSearch_tabLayout.addTab(new TabLayout(context).newTab());

我该如何修复此问题并在tabLayout中创建动态tabs

请帮助我,我真的需要您的帮助。谢谢大家 <3

1个回答

60

在您的 TabLayout 实例上调用 newTab() 函数。问题出在 new 关键字上,因为您为每个新标签创建一个新的 TabLayout 实例,并尝试将其添加到现有实例中。

fullSearch_tabLayout.addTab(fullSearch_tabLayout.newTab());

感谢您的反馈,但是根据您的描述,您希望从一个标签页创建两个标签页。例如:创建两个用户标签页,如:电影-系列-用户-用户!应该只创建一个用户标签页。 - Jongle
如何修复它? - Jongle
@Jongle 我不确定,我没有看到重复的原因。尝试调试代码,也许你会发现重复发生的时候(https://developer.android.com/studio/debug/index.html)。 - Josef Adamcik
@Jongle,也许你最初有选项卡,只需通过tab.removeAllTabs()先将它们删除。 - Adizbek Ergashev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接