使用 TabLayout 很容易实现选项卡的功能。这里将结合 ViewPager、Fragment、TabLayout实现一个具有选项卡功能的程序。本例再上篇讲解的ViewPager与Fragment实例上修改,请结合上篇实例参考。
要实现这样一个程序,首先需要在布局文件中加入 TabLayout。MainActivity中对应的布局文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:

本文介绍如何在Android应用中结合ViewPager、Fragment和TabLayout创建带有选项卡功能的程序。通过在布局文件中添加TabLayout,然后修改适配器类,最后在MainActivity中绑定TabLayout与ViewPager,实现界面切换。文中还提到了旧版API的使用问题,建议使用自定义方式以获得更好的控制选项卡行为。

696

被折叠的 条评论
为什么被折叠?



