如何通过activity添加一个TabItem?

How to add a TabItem by activity?

我需要 TabLayout 有“x”个选项卡,这可以根据数据库中已有的用户数据而变化

我的xml: enter code here

        <com.google.android.material.tabs.TabItem
            android:id="@+id/posto1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Posto Shell" />

        <com.google.android.material.tabs.TabItem
            android:id="@id/posto2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Posto Guanabara" />

我的代码:

select_bar.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
            when (tab?.position) {
                0 -> {
                    recycler_view_abastecimentos.adapter =
                        ListaAbastecimentoAdapter(applicationContext, lista)
                }
                1 -> {
                    recycler_view_abastecimentos.adapter =
                        ListaAbastecimentoAdapter(applicationContext, lista)
                }
            }
        }
 PagerAdapter pagerAdapter = new PagerAdapter(fragmentManager,
        getActivity());

mViewPager.setOffscreenPageLimit(dataCategory.size());

mViewPager.setAdapter(pagerAdapter);

mTabLayout.setupWithViewPager(mViewPager);



class PagerAdapter extends FragmentPagerAdapter {
        Context context;

        PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

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

        @Override
        public Fragment getItem(int position) {
            return SubFragment.newInstance(dataCategory.get(position),position, gridType);
         }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            // return tabTitles[position];
            return dataCategory.get(position).getCat_Name();
        }

        
    }

您可以通过以下方式进行:

 TabLayout tabLayout = ...;
 tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
 tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
 tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

在此处查看文档:https://developer.android.com/reference/com/google/android/material/tabs/TabLayout

你可以通过列一个清单来实现。从您的列表中,您可以动态创建您的选项卡。

示例:

final TabLayout tabLayout = findViewById(R.id.tab_layout);
final ArrayList<Hobby> hobbyList = getHobbyListFromDb();
if (hobbyList.size() > 0) {
   for (int i = 0; i < hobbyList.size(); i++) {
      tabLayout.addTab(tabLayout.newTab().setText(hobbyList.get(i).getName()));
   }
}