【Android】ViewPager的使用

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"tools:targetApi="31"><activityandroid:name=".MainActivity"android:exported="true"android:launchMode="singleTop"android:taskAffinity=""android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"android:hardwareAccelerated="true"android:windowSoftInputMode="adjustResize"android:background="@android:color/white"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

MainActivity.java

import android.os.Bundle;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.RadioGroup;import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;import com.cib.myapplication.adapters.AppFragmentPagerAdapter;
import com.cib.myapplication.fragments.HomeFragment;
import com.cib.myapplication.fragments.MyFragment;
import com.cib.myapplication.fragments.WalletFragment;
import com.cib.myapplication.fragments.WealthFragment;
import com.cib.myapplication.widgets.CustomRadioButton;
import com.cib.myapplication.widgets.CustomViewPager;import java.util.ArrayList;public class MainActivity extends AppCompatActivity {public CustomViewPager mViewPager;private RadioGroup mainTab;private ArrayList<Fragment> mainFraments = new ArrayList<>();private ArrayList<RadioButton> tabBars = new ArrayList<>();public HomeFragment homePageFragment;public WealthFragment wealthFragment;public WalletFragment walletFragment;public MyFragment myFragment;private AppFragmentPagerAdapter mAdapter;public static CustomRadioButton homeBar, wealthBar, walletBar, accountBar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});//findmViewPager = findViewById(R.id.activity_content);mainTab = findViewById(R.id.main_tab_views);//find tab barhomeBar = this.findViewById(R.id.bottom_bar_home);wealthBar = this.findViewById(R.id.bottom_bar_wealth);walletBar = this.findViewById(R.id.bottom_bar_wallet);accountBar = this.findViewById(R.id.bottom_bar_account);tabBars.add(homeBar);tabBars.add(wealthBar);tabBars.add(walletBar);tabBars.add(accountBar);//view pagerhomePageFragment = new HomeFragment();wealthFragment = new WealthFragment();walletFragment = new WalletFragment();myFragment = new MyFragment();mainFraments.add(homePageFragment);mainFraments.add(wealthFragment);mainFraments.add(walletFragment);mainFraments.add(myFragment);mAdapter = new AppFragmentPagerAdapter(getSupportFragmentManager(), mainFraments);mViewPager.setAdapter(mAdapter);mainTab.setOnCheckedChangeListener((group, checkedId) -> {int index = group.indexOfChild(group.findViewById(checkedId));Log.d("'QDLog'", "index " + index);mViewPager.setCurrentItem(index);});ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {int currentItem = mViewPager.getCurrentItem();tabBars.get(currentItem).setChecked(true);}@Overridepublic void onPageScrollStateChanged(int state) {}};mViewPager.addOnPageChangeListener(listener);}
}

AppFragmentPagerAdapter.java


import android.view.ViewGroup;import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.fragment.app.FragmentTransaction;import java.util.ArrayList;
import java.util.List;/*** 实现Fragment ViewPager适配器,用于App主体4个TAB页滑动切换*/
public class AppFragmentPagerAdapter extends FragmentStatePagerAdapter {private List<Fragment> mFragmentList = new ArrayList<>();private FragmentManager fm;public AppFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {super(fm);this.fm = fm;this.mFragmentList.addAll(fragmentList);}@Overridepublic Fragment getItem(int position) {return mFragmentList == null ? null : mFragmentList.get(position);}@Overridepublic int getCount() {return mFragmentList == null ? 0 : mFragmentList.size();}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {// 保证ViewPager切换过程中,page不会被销毁// super.destroyItem(container, position, object);}public int getItemPosition(Object object) {return POSITION_NONE;}@Overridepublic Object instantiateItem(ViewGroup container, int position) {return super.instantiateItem(container, position);}public void setFragmentList(List<Fragment> fragmentList) {this.mFragmentList.clear();this.mFragmentList.addAll(fragmentList);notifyDataSetChanged();}public void clearFragment() {if (this.mFragmentList != null) {FragmentTransaction fragmentTransaction = fm.beginTransaction();for (Fragment f : this.mFragmentList) {fragmentTransaction.remove(f);}fragmentTransaction.commit();fm.executePendingTransactions();}}
}

HomeFragment.java

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;import com.cib.myapplication.R;public class HomeFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_home, container, false);}
}

CustomRadioButton.java


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;import androidx.appcompat.widget.AppCompatRadioButton;import com.cib.myapplication.R;/*** 自定义底部Button*/
public class CustomRadioButton extends AppCompatRadioButton {private int mDrawableSize; // XML文件中设置的大小public CustomRadioButton(Context context) {this(context, null, 0);}public CustomRadioButton(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CustomRadioButton(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null;TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.CustomRadioButton);mDrawableSize = tArray.getDimensionPixelSize(R.styleable.CustomRadioButton_drawablesize, 50);drawableTop = tArray.getDrawable(R.styleable.CustomRadioButton_drawabletop);drawableBottom = tArray.getDrawable(R.styleable.CustomRadioButton_drawableBottom);
//        int attrCount = tArray.getIndexCount();
//        for (int i = 0; i < attrCount; i++) {
//            int attr = tArray.getIndex(i);
//            switch (attr) {
//                case R.styleable.CustomRadioButton_drawablesize:
//                    mDrawableSize = tArray.getDimensionPixelSize(R.styleable.CustomRadioButton_drawablesize, 50);
                    Log.d("appfw", "mDrawableSize:" + mDrawableSize);
//                    break;
//                case R.styleable.CustomRadioButton_drawabletop:
//                    drawableTop = tArray.getDrawable(attr);
//                    break;
//                case R.styleable.CustomRadioButton_drawableBottom:
//                    drawableBottom = tArray.getDrawable(attr);
//                    break;
//                default:
//                    break;
//            }
//        }tArray.recycle();setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom);}public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) {if (left != null) {left.setBounds(0, 0, mDrawableSize, mDrawableSize);}if (right != null) {right.setBounds(0, 0, mDrawableSize, mDrawableSize);}if (top != null) {top.setBounds(0, 0, mDrawableSize, mDrawableSize);}if (bottom != null) {bottom.setBounds(0, 0, mDrawableSize, mDrawableSize);}setCompoundDrawables(left, top, right, bottom);}}

CustomViewPager.java


import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;import androidx.viewpager.widget.ViewPager;public class CustomViewPager extends ViewPager {public CustomViewPager(Context context) {super(context);}public CustomViewPager(Context context, AttributeSet attrs) {super(context, attrs);}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {try {return super.onInterceptTouchEvent(ev);} catch (Exception ex) {ex.printStackTrace();}return false;}@Overridepublic boolean onTouchEvent(MotionEvent ev) {try {return super.onTouchEvent(ev);} catch (Exception ex) {ex.printStackTrace();}return false;}
}

activity_main.xml

<?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"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!-- App5.0为支持划动切换页面变更Content view为ViewPager--><com.cib.myapplication.widgets.CustomViewPagerandroid:id="@+id/activity_content"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white" /><!-- 自定义标签栏 --><includeandroid:id="@+id/main_tab_views"layout="@layout/bottom_bar_ver5"android:layout_width="match_parent"android:layout_height="50dp"android:layout_alignParentBottom="true" /><RelativeLayoutandroid:id="@+id/rl_older_layout"android:layout_width="match_parent"android:layout_height="56dp"android:layout_alignParentBottom="true"><Viewandroid:layout_width="match_parent"android:layout_height="1px"android:layout_alignParentBottom="true"android:layout_marginBottom="55dp"android:background="@color/devideline_bg" /></RelativeLayout></RelativeLayout><!--    <include--><!--        layout="@layout/bindkeyboard_num"--><!--        android:visibility="gone" />--><!--    <com.cib.qdzg.widgets.NumKeyBoard--><!--        android:id="@+id/num_keyboard_index"--><!--        android:layout_width="match_parent"--><!--        android:layout_height="match_parent"--><!--        android:visibility="gone" />--><!--    <include--><!--        layout="@layout/input"--><!--        android:visibility="gone" />--><!--            <ImageView--><!--                android:id="@+id/iv_advertPic"--><!--                android:layout_width="wrap_content"--><!--                android:layout_height="wrap_content"--><!--                android:visibility="gone" />--></FrameLayout>

bottom_bar_ver5.xml

<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"xmlns:radio="http://schemas.android.com/apk/res-auto"android:id="@+id/main_tab"android:layout_width="match_parent"android:layout_height="50dp"android:background="@color/white"android:orientation="horizontal"><com.cib.myapplication.widgets.CustomRadioButtonandroid:id="@+id/bottom_bar_home"style="@style/bottom_bar_item"android:checked="true"android:text="@string/tabbar_home_title"radio:drawablesize="20dp"radio:drawabletop="@drawable/bottom_bar_home_ver5" /><com.cib.myapplication.widgets.CustomRadioButtonandroid:id="@+id/bottom_bar_wealth"style="@style/bottom_bar_item"android:text="@string/tabbar_wealth_title"radio:drawablesize="20dp"radio:drawabletop="@drawable/bottom_bar_wealth_ver5" /><com.cib.myapplication.widgets.CustomRadioButtonandroid:id="@+id/bottom_bar_wallet"style="@style/bottom_bar_item"android:text="@string/tabbar_wallet_title"radio:drawablesize="20dp"radio:drawabletop="@drawable/bottom_bar_wallet_ver5" /><com.cib.myapplication.widgets.CustomRadioButtonandroid:id="@+id/bottom_bar_account"style="@style/bottom_bar_item"android:text="@string/tabbar_account_title"radio:drawablesize="20dp"radio:drawabletop="@drawable/bottom_bar_account_ver5" /></RadioGroup>

fragment_home.xml,fragment_my.xml 都一样


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Home Page"android:textSize="24sp"/>
</LinearLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><color name="purple_200">#FFBB86FC</color><color name="purple_500">#FF6200EE</color><color name="purple_700">#FF3700B3</color><color name="teal_200">#FF03DAC5</color><color name="teal_700">#FF018786</color><color name="black">#FF000000</color><color name="white">#FFFFFFFF</color><color name="bottom_bar_text_normal">#555555</color><color name="bottom_bar_text_checked">#5047FF</color><color name="transparent">#00000000</color><color name="devideline_bg">#E5E5E5</color>
</resources>

strings.xml

<resources><string name="app_name">MyApplication</string><string name="tabbar_home_title">首页</string><string name="tabbar_wealth_title">财富</string><string name="tabbar_scan_title">扫一扫</string><string name="tabbar_wallet_title">钱包</string><string name="tabbar_account_title">我的</string>
</resources>

styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><declare-styleable name="CustomRadioButton"><attr name="drawablesize" format="dimension" /><attr name="drawabletop" format="reference" /><attr name="drawableBottom" format="reference" /></declare-styleable><!-- Bottom start --><style name="bottom_bar_item"><item name="android:textSize">12sp</item><item name="android:textColor">@drawable/bottom_bar_text_color</item><item name="android:layout_width">fill_parent</item><item name="android:layout_height">fill_parent</item><item name="android:layout_weight">1</item><item name="android:gravity">center</item><item name="android:paddingTop">5dp</item><item name="android:paddingBottom">5dp</item><item name="android:drawablePadding">1.0dip</item><item name="android:button">@null</item><item name="android:background">@null</item><item name="android:clickable">true</item></style>
</resources>

themes.xml

<resources xmlns:tools="http://schemas.android.com/tools"><!-- Base application theme. --><style name="AppTheme" parent="BaseTheme"></style><style name="BaseTheme" parent="Theme.MaterialComponents.Light.NoActionBar"><item name="android:windowNoTitle">true</item><item name="android:windowFullscreen">true</item><item name="android:windowTranslucentNavigation">true</item><item name="android:windowTranslucentStatus">true</item><item name="android:windowDrawsSystemBarBackgrounds">false</item><item name="android:windowBackground">@drawable/bg_splash_layer</item></style>
</resources>

在这里插入图片描述

demo download:
demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/71740.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

京东广告基于 Apache Doris 的冷热数据分层实践

一、背景介绍 京东广告围绕Apache Doris建设广告数据存储服务&#xff0c;为广告主提供实时广告效果报表和多维数据分析服务。历经多年发展&#xff0c;积累了海量的广告数据&#xff0c;目前系统总数据容量接近1PB&#xff0c;数据行数达到18万亿行&#xff0c;日查询请求量8…

Windows PyCharm的python项目移动存储位置后需要做的变更

项目使用的venv虚拟环境&#xff0c;因此项目移动存储位置后需要重新配置python解释器的位置&#xff0c;否则无法识别&#xff0c;若非虚拟环境中运行&#xff0c;则直接移动后打开即可&#xff0c;无需任何配置。 PyCharm版本为2021.3.3 (Professional Edition)&#xff0c;其…

前后端对接

前端与后端的对接主要通过 接口 进行数据交互&#xff0c;具体流程和方式如下&#xff1a; 1. 明确需求与接口定义 前后端协商&#xff1a;确定需要哪些接口、接口的功能、请求参数和返回格式。接口文档&#xff1a;使用工具&#xff08;如 Swagger、Postman、Apifox&#xff…

简识MQ之Kafka、ActiveMQ、RabbitMQ、RocketMQ传递机制

四种主流消息队列&#xff08;Kafka、ActiveMQ、RabbitMQ、RocketMQ&#xff09;的生产者与消费者传递信息的机制说明&#xff0c;以及实际使用中的注意事项和示例&#xff1a; 1. Apache Kafka 传递机制 模型&#xff1a;基于 发布-订阅模型&#xff0c;生产者向 主题&#…

Websocket——心跳检测

1. 前言&#xff1a;为什么需要心跳机制&#xff1f; 在现代的实时网络应用中&#xff0c;保持客户端和服务端的连接稳定性是非常重要的。尤其是在长时间的网络连接中&#xff0c;存在一些异常情况&#xff0c;导致服务端无法及时感知到客户端的断开&#xff0c;可能造成不必要…

tailwindcss 前端 css 框架 无需写css 快速构建页面

版本&#xff1a;VUE3 TS 框架 vite 文章中使用tailwindcss 版本&#xff1a; ^3.4.17 简介&#xff1a; Tailwind CSS 一个CSS 框架&#xff0c;提供组件化的样式&#xff0c;直接在HTML 中编写样式&#xff0c;无需额外自定义CSS &#xff0c;快速&#xff01; 简洁&#…

MFC开发:如何创建第一个MFC应用程序

文章目录 一、概述二、MFC 的主要组件三、创建一个MFC窗口四、控件绑定消息函数 一、概述 MFC 是微软提供的一个 C 类库&#xff0c;用于简化 Windows 应用程序的开发。它封装了 Windows API&#xff0c;提供面向对象的接口&#xff0c;帮助开发者更高效地创建图形用户界面&am…

【Git版本控制器】第四弹——分支管理,合并冲突,--no-ff,git stash

&#x1f381;个人主页&#xff1a;我们的五年 &#x1f50d;系列专栏&#xff1a;Linux网络编程 &#x1f337;追光的人&#xff0c;终会万丈光芒 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 ​ 相关笔记&#xff1a; https://blog.csdn.net/djd…

AI助力小微企业技术开发规范化管理 | 杂谈

AI助力小微企业技术开发规范化管理 在小型技术研发企业中&#xff0c;人员配置紧张&#xff0c;往往一名员工需要承担多项职务和任务。例如&#xff0c;后端程序开发人员可能同时要负责需求调研、数据库设计、后端设计及开发&#xff0c;甚至在某些情况下还需兼任架构师的角色。…

SpringBoot+Vue+微信小程序的猫咖小程序平台(程序+论文+讲解+安装+调试+售后)

感兴趣的可以先收藏起来&#xff0c;还有大家在毕设选题&#xff0c;项目以及论文编写等相关问题都可以给我留言咨询&#xff0c;我会一一回复&#xff0c;希望帮助更多的人。 系统介绍 在当下这个高速发展的时代&#xff0c;网络科技正以令人惊叹的速度不断迭代更新。从 5G …

DeepSeek提效实操革命,全场景应用指南 AI提示词万能公式四步法以及对话技巧

欢迎来到涛涛聊AI DeepSeek系列文章 三块显示器如何摆放效率最高&#xff0c;让deepseek给深度思考下 阿里云免费试用 DeepSeek大模型。 限时送 100 万 tokens&#xff0c;快来抢先免费体验&#xff01;AI 助手不再出现系统繁忙阿里云免费试用 DeepSeek大模型。 限时送 100 万 …

智慧教室与无纸化同屏技术方案探讨与实现探究

引言 随着教育信息化的不断发展&#xff0c;智慧教室和无纸化同屏技术逐渐成为提升教学效率和质量的重要手段。大牛直播SDK凭借其强大的音视频处理能力和丰富的功能特性&#xff0c;在智慧教室和无纸化同屏领域积累了众多成功案例。本文将深入探讨基于大牛直播SDK的智慧教室、…

Linux MySQL 8.0.29 忽略表名大小写配置

Linux MySQL 8.0.29 忽略表名大小写配置 问题背景解决方案遇到的问题&#xff1a; 问题背景 突然发现有个大写的表报不存在。 在Windows上&#xff0c;MySQL是默认支持忽略大小写的。 这个时候你要查询一下是不是没有配置&#xff1a; SHOW VARIABLES LIKE lower_case_table…

【蓝桥杯单片机】第十三届省赛第二场

一、真题 二、模块构建 1.编写初始化函数(init.c) void Cls_Peripheral(void); 关闭led led对应的锁存器由Y4C控制关闭蜂鸣器和继电器 2.编写LED函数&#xff08;led.c&#xff09; void Led_Disp(unsigned char ucLed); 将ucLed取反的值赋给P0 开启锁存器 关闭锁存…

【CMake 教程】常用函数与构建案例解析(三)

一、CMake 常用函数简析 1. 条件判断 if() / elseif() / else() 在 CMake 脚本中&#xff0c;条件判断是控制逻辑的重要工具。if() 支持多种比较语句&#xff0c;包括数值、字符串、布尔值和变量存在性等。在条件满足时执行特定逻辑代码&#xff0c;下面是典型语法&#xff1…

ASP.NET Core 8.0学习笔记(二十七)——数据迁移:Migrations深入与其他迁移命令

一、数据库架构的管理 1.EF Core提供两种方式来保持EF Core的模型与数据库保持同步。 (1)以数据库为准&#xff1a;反向工程&#xff08;Db First&#xff09;&#xff0c;适用于中大型工程 (2)以代码为准&#xff1a;数据迁移&#xff08;Code First&#xff09;&#xff0c;…

Python 基本语法的详细解释

目录 &#xff08;1&#xff09;注释 &#xff08;2&#xff09;缩进 &#xff08;3&#xff09;变量和数据类型 变量定义 数据类型 &#xff08;4&#xff09;输入和输出 输出&#xff1a;print() 函数 输入&#xff1a;input() 函数 &#xff08;1&#xff09;注释 注…

20-R 绘图 - 饼图

R 绘图 - 饼图 R 语言提供来大量的库来实现绘图功能。 饼图&#xff0c;或称饼状图&#xff0c;是一个划分为几个扇形的圆形统计图表&#xff0c;用于描述量、频率或百分比之间的相对关系。 R 语言使用 pie() 函数来实现饼图&#xff0c;语法格式如下&#xff1a; pie(x, l…

Ubuntu 22.04 一键部署MinerU1.1.0

MinerU MinerU是一款将PDF转化为机器可读格式的工具&#xff08;如markdown、json&#xff09;&#xff0c;可以很方便地抽取为任意格式。 MinerU诞生于书生-浦语的预训练过程中&#xff0c;我们将会集中精力解决科技文献中的符号转化问题&#xff0c;希望在大模型时代为科技发…

紫光同创开发板使用教程(二):sbit文件下载

sbit文件相当于zynq里面的bit文件&#xff0c;紫光的fpga工程编译完成后会自动生成sbit文件&#xff0c;因工程编译比较简单&#xff0c;这里不在讲解工程编译&#xff0c;所以我这里直接下载sbit文件。 1.工程编译完成后&#xff0c;可以看到Flow列表里面没有报错&#xff0c…