TabLayout+ViewPager2是最常被用來實現帶有標籤的滑動視圖的其中一種方法之一。
xml屬性 | 參數 | 意思 |
---|---|---|
app:tabBackground | 16進位顏色代碼 | TabLayout背景顏色 |
app:tabIndicatorGravity | bottom; stretch; top; center | 指示器位置, 預設為"bottom" |
app:tabIndicatorColor | 16進位顏色代碼 | TabItem為選中狀態時的指示器顏色 |
app:tabSelectedTextColor | 16進位顏色代碼 | TabItem為選中狀態時的文字顏色 |
app:tabTextColor | 16進位顏色代碼 | TabItem為未選中狀態時的文字顏色 |
app:tabMode | auto; fixed; scrollable | fixed: 所有標籤會以TabLayout寬度去平均分配。 scrollable: 標籤長寬依內容決定, 且當標籤過多超過TabLayout寬度時, 會以滾動的形式呈現。 |
app:tabGravity | fill; center | fill: 所有標籤寬度一樣, 且佔滿整個TabLayout。 center: 標籤長寬依內容決定, 且集中在中間。 |
TabLayout
與ViewPager2
控件進行連動, 並設置tab標籤文字。創建一個用來顯示各標籤畫面的Fragment
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CollectionFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/page_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
public class CollectionFragment extends Fragment {
public static final String ARG_LABEL = "ARG_Label";
public static final String ARG_INDEX = "ARG_Index";
private static FragmentCollectionBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_a, container, false);
binding = FragmentCollectionBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
assert args != null;
int pageInd = args.getInt(ARG_INDEX);
String pageLabel = args.getString(ARG_LABEL);
// 顯示頁面索引和標籤值。
StringBuilder pageTextStr = new StringBuilder().append("[").append(pageInd+1).append("] ").append(pageLabel);
binding.pageText.setText(pageTextStr);
}
}
在佈局添加TabLayout和ViewPager2控件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tabGravity="start"
app:tabMode="auto" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tabLayout">
</androidx.viewpager2.widget.ViewPager2>
</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Step3 創建一個List儲存需顯示的標籤文字
List<String> tabTitles = Arrays.asList("A頁面", "B頁面", "C頁面", "D頁面", "E頁面");
// Step4 設置viewPager2的Adapter
binding.viewPager.setAdapter(
new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
@Override
public int getItemCount() {
return tabTitles.size();
}
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = new CollectionFragment();
Bundle bundle = new Bundle();
bundle.putString(CollectionFragment.ARG_LABEL, tabTitles.get(position)); // 傳遞標籤值
bundle.putInt(CollectionFragment.ARG_INDEX, position); // 傳遞索引值
fragment.setArguments(bundle);
return fragment;
}
}
);
// 設置初始選中項
binding.viewPager.setCurrentItem(1);
// 設置viewpager滑動監聽
binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
// 當tab選中項變動時調用
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(getApplicationContext(), tabTitles.get(position), Toast.LENGTH_SHORT).show();
}
});
// Step5 創建TabLayoutMediator來把`TabLayout`與`ViewPager2`關聯
new TabLayoutMediator(binding.tabLayout, binding.viewPager,
(tab, position) -> tab.setText(tabTitles.get(position)+"標籤")
).attach();
}
}
創建一個List儲存需顯示的標籤Title文字
List<String> tabTitles = Arrays.asList("A頁面", "B頁面", "C頁面", "D頁面", "E頁面");
設置ViewPager2的Adapter, 用以創建第一步所準備的Fragment和傳值操作。
binding.viewPager.setAdapter(
new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
@Override
public int getItemCount() {
return tabTitles.size();
}
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = new CollectionFragment();
Bundle bundle = new Bundle();
bundle.putString(CollectionFragment.ARG_LABEL, tabTitles.get(position)); // 傳遞標籤值
bundle.putInt(CollectionFragment.ARG_INDEX, position); // 傳遞索引值
fragment.setArguments(bundle);
return fragment;
}
}
);
創建TabLayoutMediator來把TabLayout與ViewPager2控件進行連動, 並設置tab標籤文字。
new TabLayoutMediator(binding.tabLayout, binding.viewPager,
(tab, position) -> tab.setText(tabTitles.get(position)+"標籤")
).attach();
binding.viewPager.setCurrentItem(1);
binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
// 當tab選中項變動時調用
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(getApplicationContext(), tabTitles.get(position), Toast.LENGTH_SHORT).show();
}
});