Android开发,使用TabLayout+ViewPager2实现校园健康安全宣传

文章目录

    • [1. 编写布局文件](#1. 编写布局文件)
    • [2. 代码逻辑实现](#2. 代码逻辑实现)
    • [3. 运行效果](#3. 运行效果)
    • [3. 关于作者其它项目视频教程介绍](#3. 关于作者其它项目视频教程介绍)

1. 编写布局文件

  1. fragment_home.xml
xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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">

    <!--
     设置选中时字体颜色
     app:tabSelectedTextColor="@color/purple_200"
     设置默认时字体颜色
     app:tabTextColor="#222222"
     设置指示器的宽度自适应文字的宽度
     app:tabIndicatorFullWidth="false"
     设置指示器的颜色
     app:tabIndicatorColor="@color/purple_200"
     设置超出字体内容超出一屏,可以滑动
     app:tabMode="scrollable"
    -->

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:background="@color/teal_200"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="@color/white"
        app:tabIndicatorFullWidth="false"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="#222222" />

    <View
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:background="@color/teal_200"/>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.appcompat.widget.LinearLayoutCompat>

这里注意:在布局预览效果中,并没有实际效果,原因是TabLayout并没有设置任何数据

2. 代码逻辑实现

HomeFragment.java

java 复制代码
public class HomeFragment extends Fragment {
    private View rootView;
    private String[] titles = {"健康知识宣传", "防诈骗安全知识宣传"};
    private List<Fragment> fragmentList =new ArrayList<>();
    private TabLayout tab_layout;
    private ViewPager2 viewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_home, container, false);

        //初始化控件
        tab_layout = rootView.findViewById(R.id.tab_layout);
        viewPager = rootView.findViewById(R.id.viewPager);

        //初始化数据
        fragmentList.add(new TabFirstFragment());
        fragmentList.add(new TabSecondFragment());

        //设置适配器
        viewPager.setAdapter(new FragmentStateAdapter(getActivity()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        //tab_layout点击事件
        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //设置viewPager选中当前页
                viewPager.setCurrentItem(tab.getPosition(),false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //viewPager和tab_layout关联在一起
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tab_layout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(titles[position]);
            }
        });

        //这几话不能少
        tabLayoutMediator.attach();

        return rootView;
    }
}

注意事项:

  • 这里我是在Fragment里面去实现的,不是在Activity中,如果你想在Activity中去实现,初始化控件直接findViewById(R.id.xxx)就可以了
  • viewPager.setAdapter(new FragmentStateAdapter(getActivity())在Fragment中使用getActivity() 在Activity中请使用this即可
  • TabFirstFragment TabSecondFragment就是Fragment页面,自己创建就好,没有逻辑代码

3. 运行效果

3. 关于作者其它项目视频教程介绍

本人在b站录制的一些视频教程项目,免费供大家学习

  1. Android新闻资讯app实战:https://www.bilibili.com/video/BV1CA1vYoEad/?vd_source=984bb03f768809c7d33f20179343d8c8
  2. Androidstudio开发购物商城实战:https://www.bilibili.com/video/BV1PjHfeXE8U/?vd_source=984bb03f768809c7d33f20179343d8c8
  3. Android开发备忘录记事本实战:https://www.bilibili.com/video/BV1FJ4m1u76G?vd_source=984bb03f768809c7d33f20179343d8c8&spm_id_from=333.788.videopod.sections
  4. Androidstudio底部导航栏实现:https://www.bilibili.com/video/BV1XB4y1d7et/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
  5. Android使用TabLayout+ViewPager2实现左右滑动切换:https://www.bilibili.com/video/BV1Mz4y1c7eX/?spm_id_from=333.337.search-card.all.click&vd_source=984bb03f768809c7d33f20179343d8c8
相关推荐
麦兜*1 天前
【swift】SwiftUI动画卡顿全解:GeometryReader滥用检测与Canvas绘制替代方案
服务器·ios·swiftui·android studio·objective-c·ai编程·swift
编程乐学1 天前
网络资源模板--基于Android Studio 实现的通讯录App
android·android studio·移动端开发·通讯录app·安卓大作业
bytebeats1 天前
# Android Studio Narwhal Agent 模式简介
android·android studio
小仙女喂得猪4 天前
2025再读Android RecyclerView源码
android·android studio
一枚小小程序员哈4 天前
基于Android的音乐播放器/基于android studio的音乐系统/音乐管理系统
android·ide·android studio
沅霖7 天前
下载Android studio
android·ide·android studio
沅霖9 天前
Android Studio切换到经典UI,老UI
android·ui·android studio
闻道且行之11 天前
Android Studio下载及安装配置
android·ide·android studio
小墙程序员11 天前
kotlin元编程(二)使用 Kotlin 来生成源代码
android·kotlin·android studio
小墙程序员11 天前
kotlin元编程(一)一文理解 Kotlin 反射
android·kotlin·android studio