以下是一个示例代码,展示了如何在 ViewPage2 和 TabLayout 中使用自定义选项卡样式:

  1. 首先,在布局文件中添加 TabLayout 和 ViewPager:
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed"
    app:tabIndicatorHeight="2dp"
    app:tabBackground="@drawable/tab_selector"/>

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. 创建自定义选项卡样式的 Drawable,例如 tab_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@color/colorAccent" />
    <item android:state_focused="true" android:color="@color/colorPrimaryDark" />
    <item android:state_pressed="true" android:color="@color/colorPrimaryDark" />
    <item android:color="@color/colorPrimary" />
</selector>
  1. 在 Activity 或 Fragment 中初始化 TabLayout 和 ViewPager,并将它们绑定起来:
// 初始化TabLayout
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText('Tab 1'));
tabLayout.addTab(tabLayout.newTab().setText('Tab 2'));
tabLayout.addTab(tabLayout.newTab().setText('Tab 3'));

// 初始化ViewPager
ViewPager2 viewPager = findViewById(R.id.view_pager);
MyPagerAdapter myPagerAdapter = new MyPagerAdapter(this);
viewPager.setAdapter(myPagerAdapter);

// 将TabLayout和ViewPager绑定起来
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager,
        (tab, position) -> tab.setText('Tab ' + (position + 1)));
tabLayoutMediator.attach();
  1. 可选:如果需要更多自定义选项卡样式,可以创建自定义 TabLayout.Tab 的子类,并在 TabLayoutMediator 中使用它:
class MyTab extends TabLayout.Tab {
    public MyTab(View customView) {
        super(customView);
    }
}

// 在Activity或Fragment中使用自定义TabLayout.Tab
TabLayout tabLayout = findViewById(R.id.tab_layout);
MyTab tab1 = new MyTab(getLayoutInflater().inflate(R.layout.tab_custom, null));
MyTab tab2 = new MyTab(getLayoutInflater().inflate(R.layout.tab_custom, null));
MyTab tab3 = new MyTab(getLayoutInflater().inflate(R.layout.tab_custom, null));
tabLayout.addTab(tab1);
tabLayout.addTab(tab2);
tabLayout.addTab(tab3);

// 在TabLayoutMediator中使用自定义TabLayout.Tab
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager,
        (tab, position) -> {
            View customView = LayoutInflater.from(this).inflate(R.layout.tab_custom, null);
            ImageView icon = customView.findViewById(R.id.icon);
            TextView text = customView.findViewById(R.id.text);
            icon.setImageResource(tabIcons[position]);
            text.setText(tabTitles[position]);
            tab.setCustomView(customView);
        });
tabLayoutMediator.attach();
Android ViewPage2 与 TabLayout 自定义选项卡样式示例

原文地址: https://www.cveoy.top/t/topic/oV28 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录