我需要 TabLayout 有“x”個選項卡,這可能會根據資料庫中已經存在的用戶資料而有所不同
我的 xml:
enter code here<com.google.android.material.tabs.TabLayout android:id="@ id/select_bar" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf ="父" 應用程式:layout_constraintTop_toTopOf="父" 應用程式:tabContentStart="32dp" 應用程式:tabMode="scrollable">
<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)
}
}
}
uj5u.com熱心網友回復:
你可以這樣做:
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
uj5u.com熱心網友回復:
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();
}
}
uj5u.com熱心網友回復:
您可以通過列出清單來實作這一點。從您的串列中,您可以動態創建選項卡。
例子:
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()));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460526.html
