ViewPager+fragment实现切换页面(一)

2024-09-08 08:48

本文主要是介绍ViewPager+fragment实现切换页面(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

如今的很多应用中都是下面有一排按钮,点击可以切换页面,滑动也可以切换页面。下面就来简单的实现这个功能。

思路
  • 首先肯定是会用到viewpager这个控件,为了能够向下兼容,最好用v4包下的viewpager,Activity要继承FragmentActivity
  • 其次用一个集合来存储所有的fragment页面
  • 在设置viewpager的适配器时,把存储fragment页面的list集合传入adapter中,adapter继承的是FragmentPagerAdapter
  • 给viewpager设置监听事件,这样滑动换页的时候做相应的逻辑处理
  • 点击按钮想要得到对应的fragment页面,只需要设置viewpager.setCurrentItem(item);

  • 遗忘的一个概念 object[] obj = new object[]任何对象都可以创建数组

效果图

这里写图片描述

这里写图片描述

下面上代码
主界面布局代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="#ededed"><RelativeLayout android:layout_width="match_parent"android:layout_height="50dp"android:background="#ffffff"><TextView android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="20sp"android:text="个人信息"android:textColor="#ed6d48"android:layout_marginTop="10dp"android:layout_marginBottom="10dp"android:layout_centerInParent="true"/></RelativeLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:background="@drawable/linearlayout01"android:orientation="horizontal"android:weightSum="5" ><LinearLayout
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="15dp"android:layout_marginLeft="20dp"android:layout_marginTop="15dp"android:layout_weight="2"android:gravity="center"android:orientation="vertical" ><TextView
                android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="账户总额"android:textSize="12sp" /><LinearLayout
                android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:orientation="horizontal" ><TextView
                    android:id="@+id/tv_shouldmoney"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="0.00"android:textColor="#ed6d48"android:textSize="20sp" /><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="元"android:textColor="#ed6d48"android:textSize="16sp" /></LinearLayout></LinearLayout><LinearLayout
            android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="15dp"android:layout_marginLeft="30dp"android:layout_marginTop="15dp"android:layout_weight="3"android:gravity="center_vertical"android:orientation="vertical" ><LinearLayout
                android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal" ><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="共消费:" /><TextView
                    android:id="@+id/tv_totalMoneyNum"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="0"android:textColor="#ed6d48" /><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="笔" /></LinearLayout><LinearLayout
                android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal" ><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="合计金额:" /><TextView
                    android:id="@+id/tv_totalMoney"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="0.00"android:textColor="#ed6d48" /><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="元" /></LinearLayout><LinearLayout
                android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal" ><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="信用额度:" /><TextView
                    android:id="@+id/tv_credit"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="5000.00"android:textColor="#ed6d48" /><TextView
                    android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="元" /></LinearLayout></LinearLayout></LinearLayout><include layout="@layout/tab"/><android.support.v4.view.ViewPager
        android:id="@+id/viewPager"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
tab布局代码
<?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="44dp"android:orientation="horizontal" android:background="#ededed"><Button android:id="@+id/btn_one"android:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"android:text="第一页"android:background="@drawable/linearlayout01"android:layout_marginLeft="5dp"android:layout_marginRight="5dp"/><Button android:id="@+id/btn_two"android:layout_width="0dp"android:layout_marginLeft="5dp"android:layout_marginRight="5dp"android:layout_weight="1"android:layout_height="wrap_content"android:background="@drawable/linearlayout01"android:text="第二页"/><Button android:id="@+id/btn_three"android:layout_marginLeft="5dp"android:layout_marginRight="5dp"android:background="@drawable/linearlayout01"android:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"android:text="第三页"/></LinearLayout>
一些资源的xml代码,比如linearLayout01.xml,linearLayout01s.xml,color.xml
linearLayout01.xml代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" ><solid android:color="#ffffff" /> <stroke android:width="0.1dip" android:color="#ed6d48" />  <corners android:radius="5dp"/></shape>
linearLayout01s.xml代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" ><solid android:color="#ffffff" /> <stroke android:width="1dip" android:color="#ed6d48" />  <corners android:radius="5dp"/></shape>
color.xml代码
<?xml version="1.0" encoding="utf-8"?>
<resources><color name="textcolor">#ed6d48</color><color name="loan_title">#ed6d48</color><color name="main_color_white">#ffffff</color><color name="background">#ededed</color><color name="loan_butBackground">#ed6d48</color><color name="black">#000000</color></resources>
MainActivity代码
 package com.example.myviewpager;import java.util.ArrayList;
import java.util.List;import com.example.adapter.MyAdapter;
import com.example.fragment.Fragment1;
import com.example.fragment.Fragment2;
import com.example.fragment.Fragment3;import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends FragmentActivity implements OnClickListener{private ViewPager mViewPager;private Button btnOne;private Button btnTwo;private Button btnThree;private Button[] btns = new Button[3];//存放fragment的集合private List<Fragment> fragmentList = new ArrayList<Fragment>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initData();initView();}private void initData() {//把fragment添加进集合fragmentList.add(new Fragment1());fragmentList.add(new Fragment2());fragmentList.add(new Fragment3());}private void initView() {btnOne = (Button) this.findViewById(R.id.btn_one);btnTwo = (Button) this.findViewById(R.id.btn_two);btnThree = (Button) this.findViewById(R.id.btn_three);//默认第一个按钮为选中状态btnOne.setBackgroundResource(R.drawable.linearlayout01s);btnOne.setTextColor(getResources().getColor(R.color.textcolor));//创建一个数组来存btn,object[] obj = new object[]这个概念才有btns[0] = btnOne;btns[1] = btnTwo;btns[2] = btnThree;btnOne.setOnClickListener(this);btnTwo.setOnClickListener(this);btnThree.setOnClickListener(this);mViewPager = (ViewPager) this.findViewById(R.id.viewPager);//设置viewpager的数据适配器mViewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), fragmentList));//监听viewpager的滑动事件,来控制按钮的变换mViewPager.setOnPageChangeListener(new OnPageChangeListener() {@Overridepublic void onPageSelected(int position) {//把3个按钮全部设置成原始状态resetButton();btns[position].setBackgroundResource(R.drawable.linearlayout01s);btns[position].setTextColor(getResources().getColor(R.color.textcolor));}@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {}@Overridepublic void onPageScrollStateChanged(int arg0) {}});}//重置button的背景和字体颜色protected void resetButton() {for(int i=0;i<btns.length;i++){btns[i].setBackgroundResource(R.drawable.linearlayout01);btns[i].setTextColor(getResources().getColor(R.color.black));}}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_one:resetButton();mViewPager.setCurrentItem(0);btns[0].setBackgroundResource(R.drawable.linearlayout01s);btns[0].setTextColor(getResources().getColor(R.color.textcolor));break;case R.id.btn_two:resetButton();mViewPager.setCurrentItem(1);btns[1].setBackgroundResource(R.drawable.linearlayout01s);btns[1].setTextColor(getResources().getColor(R.color.textcolor));break;case R.id.btn_three:resetButton();mViewPager.setCurrentItem(2);btns[2].setBackgroundResource(R.drawable.linearlayout01s);btns[2].setTextColor(getResources().getColor(R.color.textcolor));break;default:break;}}}
MyAdapter中的代码
package com.example.adapter;import java.util.List;import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;public class MyAdapter extends FragmentPagerAdapter {//接受fragment页的集合数据private List<Fragment> list;public MyAdapter(FragmentManager fm,List<Fragment> list) {super(fm);this.list = list;}@Overridepublic Fragment getItem(int position) {return list.get(position);}@Overridepublic int getCount() {return list.size();}}
其中的一个Fragment页面的代码,其余的都一样
package com.example.fragment;import com.example.myviewpager.R;import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;public class Fragment1 extends Fragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment01, null);return view;}}

下面附上完整demo的链接,里面有很详细的注释。
完整代码下载地址: http://download.csdn.net/detail/u013467495/8494827

这篇关于ViewPager+fragment实现切换页面(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147656

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现