Android 如何在 TabLayout 中以编程方式创建选项卡

How to create programmatically Tabs in TabLayout on Android

为什么没有人帮助我?

在我的应用程序中,我想在 tabLayout 中动态创建 tabs 并且我希望在从服务器 获取数据时 和此数据 count > 0 然后创建 tab.
对于 TabLayout,我使用这个库:https://github.com/egemenmede/etiyabadgetab

为了这个工作我写了下面的代码:

public class FullSearch extends AppCompatActivity {

    @BindView(R.id.fullSearch_tabLayout)
    BadgeTabLayout fullSearch_tabLayout;
    @BindView(R.id.fullSearch_ViewPager)
    ViewPager fullSearch_ViewPager;
    @BindView(R.id.toolbarTitleTxt)
    TextView toolbarTitleTxt;
    @BindView(R.id.fullSearch_LoadLay)
    RelativeLayout fullSearch_LoadLay;
    @BindView(R.id.fullSearch_ReloadLay)
    RelativeLayout fullSearch_ReloadLay;
    @BindView(R.id.fullSearch_NoNet)
    RelativeLayout fullSearch_NoNet;
    private Context context;
    private Bundle bundle;
    private String fullSearchText;
    private final String[] tabsName = {"Movies", "Series", "Episodes", "Celebrities", "Users"};
    private List<Movie> movieList = new ArrayList<>();
    private List<Series> seriesList = new ArrayList<>();
    private List<Celebrity> celebrityList = new ArrayList<>();
    private List<User> userList = new ArrayList<>();
    private int movieCount, serieCount, episodesCount, celebritiesCount, usersCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_search);

        // Initialize
        ButterKnife.bind(this);
        context = this;
        bundle = getIntent().getExtras();
        fullSearchText = bundle.getString(ExtraContains.FULL_SEARCH_TEXT.name());

        toolbarTitleTxt.setText(fullSearchText);

        // set viewPager to tabLayout
        fullSearch_tabLayout.setupWithViewPager(fullSearch_ViewPager);

        // customize tab layout
        fullSearch_tabLayout.setSelectedTabIndicatorColor(context.getResources().getColor(R.color.colorAccent));
        fullSearch_tabLayout.setSelectedTabIndicatorHeight(5);
        fullSearch_tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        fullSearch_tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

        fullSearch_LoadLay.setVisibility(View.GONE);

        getData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //checkNet();
        //fullSearch_LoadLay.setVisibility(View.GONE);
    }

    private void getData() {
        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().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().getEpisodesCount() > 0) {
                    episodesCount = searchResponse.getData().getEpisodesCount();
                }
                if (searchResponse.getData().getCelebritiesCount() > 0) {
                    celebritiesCount = searchResponse.getData().getCelebritiesCount();
                    celebrityList.clear();
                    celebrityList.addAll(searchResponse.getData().getCelebrities());
                }
                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 (movieCount > 0) {
            fullSearch_tabLayout.selectEtiyaBadgeTab(0)
                    .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.selectEtiyaBadgeTab(1)
                    .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 (episodesCount > 0) {
            fullSearch_tabLayout.selectEtiyaBadgeTab(2)
                    .tabTitle("Episodes")
                    .tabTitleColor(R.color.white)
                    .tabBadge(true)
                    .tabBadgeCount(episodesCount)
                    .tabBadgeCountMore(false)
                    .tabBadgeBgColor(R.color.colorAccent)
                    .tabBadgeTextColor(R.color.white)
                    .tabBadgeStroke(2, R.color.white)
                    .tabBadgeCornerRadius(15)
                    .createEtiyaBadgeTab();
        }
        if (celebritiesCount > 0) {
            fullSearch_tabLayout.selectEtiyaBadgeTab(3)
                    .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 (usersCount > 0) {
            fullSearch_tabLayout.selectEtiyaBadgeTab(4)
                    .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 (movieCount > 0)
            adapter.addFrag(FullSearchMovieFragment.getInstance(movieList, movieCount, fullSearchText), "Movies");
        if (serieCount > 0)
            adapter.addFrag(FullSearchSeriesFragment.getInstance(seriesList, serieCount, fullSearchText), "Series");
        if (episodesCount > 0)
            adapter.addFrag(FullSearchEpisodeFragment.getInstance(seriesList, episodesCount, fullSearchText), "Episodes");
        if (celebritiesCount > 0)
            adapter.addFrag(FullSearchCelebritiesFragment.getInstance(celebrityList, celebritiesCount, fullSearchText), "Celebrities");
        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);
        }
    }

但是当 运行 应用程序向我显示此错误时:

FATAL EXCEPTION: main
Process: com.example.sample, PID: 16981
java.lang.IllegalArgumentException: Tab null olmamali.
at com.example.sample.Utils.Componenets.BadgeTabLayout.selectEtiyaBadgeTab(BadgeTabLayout.java:73)
at com.example.sample.Activities.FullSearch.setupTabs(FullSearch.java:216)
at com.example.sample.Activities.FullSearch.access00(FullSearch.java:44)
at com.example.sample.Activities.FullSearch.onResponse(FullSearch.java:160)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.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)

当点击错误消息中的第一个 link 时,转到此代码:

public EtiyaBadgeTabBuilder selectEtiyaBadgeTab(int position) {
    Tab tab = getTabAt(position);

    if (tab == null) throw new IllegalArgumentException("Tab null olmamali.");

    EtiyaBadgeTabBuilder builder = mTabBuilders.get(tab.getPosition());
    if (builder == null) {
        builder = new EtiyaBadgeTabBuilder(this, tab);
        mTabBuilders.put(tab.getPosition(), builder);
    }

    return builder;

如何解决这个问题并在 tabLayout 中动态创建 tabs

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

试试这个。

 private void setupTabs() {
        if (movieCount > 0) {
            fullSearch_tabLayout.addTab(fullSearch_tabLayout.newTab());
            fullSearch_tabLayout.selectEtiyaBadgeTab(fullSearch_tabLayout.getTabCount()-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(fullSearch_tabLayout.newTab());
            fullSearch_tabLayout.selectEtiyaBadgeTab(fullSearch_tabLayout.getTabCount()-1)
                    .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 (episodesCount > 0) {
           fullSearch_tabLayout.addTab(fullSearch_tabLayout.newTab());
            fullSearch_tabLayout.selectEtiyaBadgeTab(fullSearch_tabLayout.getTabCount()-1)
                    .tabTitle("Episodes")
                    .tabTitleColor(R.color.white)
                    .tabBadge(true)
                    .tabBadgeCount(episodesCount)
                    .tabBadgeCountMore(false)
                    .tabBadgeBgColor(R.color.colorAccent)
                    .tabBadgeTextColor(R.color.white)
                    .tabBadgeStroke(2, R.color.white)
                    .tabBadgeCornerRadius(15)
                    .createEtiyaBadgeTab();
        }
        if (celebritiesCount > 0) {
       fullSearch_tabLayout.addTab(fullSearch_tabLayout.newTab());
            fullSearch_tabLayout.selectEtiyaBadgeTab(fullSearch_tabLayout.getTabCount()-1)
                    .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 (usersCount > 0) {
          fullSearch_tabLayout.addTab(fullSearch_tabLayout.newTab());
            fullSearch_tabLayout.selectEtiyaBadgeTab(fullSearch_tabLayout.getTabCount()-1)
                    .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();
        }
    }

和我的测试代码:

   EtiyaBadgeTab tab = (EtiyaBadgeTab) findViewById(R.id.tabbadgelayout);
    tab.addTab(tab.newTab());
    tab.addTab(tab.newTab());
    tab.addTab(tab.newTab());
    tab.selectEtiyaBadgeTab(0)
            .tabTitle("11111")
            .tabBadge(true)
            .tabBadgeCount(22)
            .tabBadgeCountMore(false)
            .tabBadgeCornerRadius(15)
            .createEtiyaBadgeTab();

    tab.selectEtiyaBadgeTab(1)
            .tabTitle("22222")
            .tabBadge(true)
            .tabBadgeCount(22)
            .tabBadgeCountMore(false)
            .tabBadgeCornerRadius(15)
            .createEtiyaBadgeTab();
    tab.selectEtiyaBadgeTab(2)
            .tabTitle("33333")
            .tabBadge(true)
            .tabBadgeCount(22)
            .tabBadgeCountMore(false)
            .tabBadgeCornerRadius(15)
            .createEtiyaBadgeTab();