安卓使用TabLayout+ViewPager+Fragment 实现页面切换,可实现左右滑动切换视图界面和点击切换

可自定义菜单栏是在顶部还是在底部

一、实现效果:

二、实现过程:

2.1 一些重要的设置

 添加必须依赖:

因为需要使用:import android.support.design.widget.TabLayout;,所以必须添加下列依赖

  1. compile 'com.android.support:design:23.3.0'

使用Android Studio3时,此步可能出现问题,请参考下面的升级篇

主布局文件编写:

顶部或者底部显示,只要更改ViewPager和TabLayout排列顺序即可

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. xmlns:app="http://schemas.android.com/apk/res-auto"
  7. android:paddingBottom="0dp"
  8. android:paddingLeft="0dp"
  9. android:paddingRight="0dp"
  10. android:orientation="vertical"
  11. android:paddingTop="0dp"
  12. tools:context="com.example.fafa.MainActivity">
  13.  
  14. <android.support.v4.view.ViewPager
  15. android:id="@+id/viewpager"
  16. android:layout_width="match_parent"
  17. android:layout_height="0dp"
  18. android:layout_weight="1"
  19. />
  20. <!--
  21. app:tabIndicatorColor="" 指示器颜色
  22. app:tabIndicatorHeight="" 指示器高度,设置为0就是没有指示器
  23. app:tabTextColor="" Tab文本默认颜色
  24. app:tabSelectedTextColor="" Tab文本被选中后的颜色
  25. app:tabTextAppearance="" 为Tab文本设置样式,一般是需要为Tab加图标时使用
  26. app:tabMode="" 只有两个值:fixed、scrollable
  27. 其中 fixed用于标题栏少的情况,每个Tab可以平分屏幕宽度
  28. 其中 scrollable用于标题栏多出屏幕的情况,如果标题栏少的时候用很难看,占不满屏幕
  29. app:tabGravity="center" 整体居中,不可与上共用
  30. app:tabBackground="" TabLayout背景,和android:background=""效果一样
  31. app:tabGravity="" 对齐方式: 居中显示center、fill填满
  32. -->
  33.  
  34. <android.support.design.widget.TabLayout
  35. android:id="@+id/tabs2"
  36. android:layout_width="match_parent"
  37. android:layout_height="wrap_content"
  38. android:layout_gravity="center"
  39.  
  40. app:tabMode="fixed"
  41. app:tabIndicatorColor="@color/colorLv"
  42. app:tabTextColor="@android:color/black"
  43. app:tabSelectedTextColor="@color/colorred"
  44.  
  45. />
  46. </LinearLayout>

2.2 仅字符菜单栏显示实现:

未加入图片显示,实现较为简单

基本逻辑代码:

每个界面使用不同的fragment,进行一 一对应

  1. import android.support.design.widget.TabLayout;
  2. public class MainActivity extends AppCompatActivity {
  3. private ViewPager viewPager;
  4. private TabLayout tabLayout;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9.  
  10. tabLayout = (TabLayout) findViewById(R.id.tabs2);
  11. viewPager = (ViewPager) findViewById(R.id.viewpager);
  12.  
  13. //设置界面文件和文字一一对应
  14. final Fragment[] fragments = {new Fragment0(), new Fragment1(), new Fragment2()};
  15. final String[] titles = {"界面1", "界面2", "界面3"};
  16.  
  17. //添加tablayout中的竖线,每一项的中间分隔线
  18. //LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
  19. // linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
  20. // linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.mipmap.fg));
  21.  
  22. //每项只进入一次
  23. viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
  24. @Override
  25. public Fragment getItem(int position) {
  26. return fragments[position];
  27. }
  28. @Override
  29. public int getCount() {
  30. return fragments.length;
  31. }
  32.  
  33. @Override
  34. public CharSequence getPageTitle(int position) {
  35. return titles[position];
  36. }
  37. });
  38.  
  39. tabLayout.setupWithViewPager(viewPager);
  40. tabLayout.getTabAt(1).select();//设置第一个为选中
  41. }
  42. }

2.3 字符和图片菜单栏实现

图片加汉字菜单栏,菜单栏每项都是一个视图可以自定义设计

菜单栏每项的布局文件设计:

一个图片显示和一个文字显示,定义为垂直布局,其中android:layout_gravity="center"是把控件居中,这里不写,在菜单栏显示时可能会出现错位

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:orientation="vertical"
  5. android:id="@+id/item_view"
  6.  
  7. android:layout_height="match_parent">
  8. <ImageView
  9. android:layout_width="wrap_content"
  10. android:src="@mipmap/ic_launcher"
  11. android:id="@+id/item_img"
  12. android:layout_gravity="center"
  13. android:layout_height="wrap_content" />
  14. <TextView
  15. android:layout_width="wrap_content"
  16. android:text="xxxx"
  17. android:layout_gravity="center"
  18. android:id="@+id/item_text"
  19. android:layout_height="wrap_content" />
  20. </LinearLayout>

 

主布局文件更改:

在主布局文件的<android.support.design.widget.TabLayout>更改android:layout_height="70dp",表示其菜单栏的高度改变。

定义必要的类变量:

  1. private ViewPager viewPager;
  2. private TabLayout tabLayout;
  3. //设置界面文件和文字一一对应
  4. private Fragment[] Lfragments = {new Fragment0(), new Fragment1(), new Fragment2(),new Fragment3()};
  5. private String[] Ltitles = {"界面1", "界面2", "界面3","界面4"};
  6. //未选中图片
  7. private int[] Limg = {R.mipmap.an1,R.mipmap.an2,R.mipmap.an3,R.mipmap.an4};
  8. //选中图片
  9. private int[] Limgn = {R.mipmap.ann1,R.mipmap.ann2,R.mipmap.ann3,R.mipmap.ann4};
  10. //配置默认选中第几项
  11. private int ItemWhat=1;

数据初始化及基本界面加载:

  1. //只进入一次,初始化
  2. viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
  3. @Override
  4. public Fragment getItem(int position) {
  5. return Lfragments[position];
  6. }
  7. @Override
  8. public int getCount() {
  9. return Lfragments.length;
  10. }
  11.  
  12. @Override
  13. public CharSequence getPageTitle(int position) {
  14. return Ltitles[position];
  15. }
  16. });
  17.  
  18. //绑定
  19. tabLayout.setupWithViewPager(viewPager);
  20.  
  21. //设置默认选中页,宏定义
  22. tabLayout.getTabAt(ItemWhat).select();
  23. viewPager.setOffscreenPageLimit(3); //设置向左和向右都缓存的页面个数
  24. //初始化菜单栏显示
  25. for (int i = 0; i < tabLayout.getTabCount(); i++) {
  26. //寻找到控件
  27. View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.items, null);
  28. LinearLayout mTabView = (LinearLayout) view.findViewById(R.id.item_view);
  29. TextView mTabText = (TextView) view.findViewById(R.id.item_text);
  30. ImageView mTabIcon = (ImageView) view.findViewById(R.id.item_img);
  31.  
  32. mTabText.setText(Ltitles[i]);
  33. mTabIcon.setImageResource(Limg[i]);
  34. //设置不可点击
  35. // mTabView.setClickable(true);
  36.  
  37. //更改选中项样式
  38. if(i==ItemWhat){
  39. mTabIcon.setImageResource(Limgn[i]);
  40. mTabText.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
  41. }
  42.  
  43. //设置样式
  44. tabLayout.getTabAt(i).setCustomView(view);
  45. }

监听选择事件:

  1. //是否选中监听
  2. tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
  3. @Override
  4. public void onTabSelected(TabLayout.Tab tab) {
  5. //选中时进入,改变样式
  6. ItemSelect(tab);
  7. //onTabselected方法里面调用了viewPager的setCurrentItem 所以要想自定义OnTabSelectedListener,也加上mViewPager.setCurrentItem(tab.getPosition())就可以了
  8. viewPager.setCurrentItem(tab.getPosition());
  9. }
  10.  
  11. @Override
  12. public void onTabUnselected(TabLayout.Tab tab) {
  13. //未选中进入,改变样式
  14. ItemNoSelect(tab);
  15.  
  16. }
  17.  
  18. @Override
  19. public void onTabReselected(TabLayout.Tab tab) {
  20. //重新选中
  21.  
  22. }
  23. });

选中和非选中,更改其中显示样式:

  1. //某个项选中,改变其样式
  2. private void ItemSelect(TabLayout.Tab tab) {
  3. View customView = tab.getCustomView();
  4. TextView tabText = (TextView) customView.findViewById(R.id.item_text);
  5. ImageView tabIcon = (ImageView) customView.findViewById(R.id.item_img);
  6. tabText.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
  7. String stitle = tabText.getText().toString();
  8. for(int i=0;i<Ltitles.length;i++){
  9. if(Ltitles[i].equals(stitle)){
  10. //Toast.makeText(MainActivity.this,"xxx+"+i,Toast.LENGTH_SHORT).show();
  11. tabIcon.setImageResource(Limgn[i]);
  12. }
  13. }
  14. }
  15. //某个项非选中,改变其样式
  16. private void ItemNoSelect(TabLayout.Tab tab) {
  17. View customView = tab.getCustomView();
  18. TextView tabText = (TextView) customView.findViewById(R.id.item_text);
  19. ImageView tabIcon = (ImageView) customView.findViewById(R.id.item_img);
  20. tabText.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
  21. String stitle = tabText.getText().toString();
  22. for(int i=0;i<Ltitles.length;i++){
  23. if(Ltitles[i].equals(stitle)){
  24. tabIcon.setImageResource(Limg[i]);
  25. }
  26. }
  27. }

整体代码:

  1. import android.support.design.widget.TabLayout;
  2. public class MainActivity extends AppCompatActivity {
  3. private ViewPager viewPager;
  4. private TabLayout tabLayout;
  5. //设置界面文件和文字一一对应
  6. private Fragment[] Lfragments = {new Fragment0(), new Fragment1(), new Fragment2(),new Fragment3()};
  7. private String[] Ltitles = {"界面1", "界面2", "界面3","界面4"};
  8. //未选中图片
  9. private int[] Limg = {R.mipmap.an1,R.mipmap.an2,R.mipmap.an3,R.mipmap.an4};
  10. //选中图片
  11. private int[] Limgn = {R.mipmap.ann1,R.mipmap.ann2,R.mipmap.ann3,R.mipmap.ann4};
  12. //配置默认选中第几项
  13. private int ItemWhat=1;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18.  
  19. //找控件
  20. tabLayout = (TabLayout) findViewById(R.id.tabs2);
  21. viewPager = (ViewPager) findViewById(R.id.viewpager);
  22.  
  23. //添加tablayout中的竖线,每一项的中间分隔线
  24. //LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
  25. // linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
  26. // linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.mipmap.fg));
  27.  
  28. //只进入一次,初始化
  29. viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
  30. @Override
  31. public Fragment getItem(int position) {
  32. return Lfragments[position];
  33. }
  34. @Override
  35. public int getCount() {
  36. return Lfragments.length;
  37. }
  38.  
  39. @Override
  40. public CharSequence getPageTitle(int position) {
  41. return Ltitles[position];
  42. }
  43. });
  44.  
  45. //绑定
  46. tabLayout.setupWithViewPager(viewPager);
  47.  
  48. //设置默认选中页,宏定义
  49. tabLayout.getTabAt(ItemWhat).select();
  50. viewPager.setOffscreenPageLimit(3); //设置向左和向右都缓存的页面个数
  51. //初始化菜单栏显示
  52. for (int i = 0; i < tabLayout.getTabCount(); i++) {
  53. //寻找到控件
  54. View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.items, null);
  55. LinearLayout mTabView = (LinearLayout) view.findViewById(R.id.item_view);
  56. TextView mTabText = (TextView) view.findViewById(R.id.item_text);
  57. ImageView mTabIcon = (ImageView) view.findViewById(R.id.item_img);
  58.  
  59. mTabText.setText(Ltitles[i]);
  60. mTabIcon.setImageResource(Limg[i]);
  61. //设置不可点击
  62. // mTabView.setClickable(true);
  63.  
  64. //更改选中项样式
  65. if(i==ItemWhat){
  66. mTabIcon.setImageResource(Limgn[i]);
  67. mTabText.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
  68. }
  69.  
  70. //设置样式
  71. tabLayout.getTabAt(i).setCustomView(view);
  72. }
  73. //是否选中监听
  74. tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
  75. @Override
  76. public void onTabSelected(TabLayout.Tab tab) {
  77. //选中时进入,改变样式
  78. ItemSelect(tab);
  79. //onTabselected方法里面调用了viewPager的setCurrentItem 所以要想自定义OnTabSelectedListener,也加上mViewPager.setCurrentItem(tab.getPosition())就可以了
  80. viewPager.setCurrentItem(tab.getPosition());
  81. }
  82. @Override
  83. public void onTabUnselected(TabLayout.Tab tab) {
  84. //未选中进入,改变样式
  85. ItemNoSelect(tab);
  86. }
  87. @Override
  88. public void onTabReselected(TabLayout.Tab tab) {
  89. //重新选中
  90.  
  91. }
  92. });}
  93. //某个项选中,改变其样式
  94. private void ItemSelect(TabLayout.Tab tab) {
  95. View customView = tab.getCustomView();
  96. TextView tabText = (TextView) customView.findViewById(R.id.item_text);
  97. ImageView tabIcon = (ImageView) customView.findViewById(R.id.item_img);
  98. tabText.setTextColor(ContextCompat.getColor(this, R.color.colorRed));
  99. String stitle = tabText.getText().toString();
  100. for(int i=0;i<Ltitles.length;i++){
  101. if(Ltitles[i].equals(stitle)){
  102. //Toast.makeText(MainActivity.this,"xxx+"+i,Toast.LENGTH_SHORT).show();
  103. tabIcon.setImageResource(Limgn[i]);
  104. }
  105. }
  106. }
  107. //某个项非选中,改变其样式
  108. private void ItemNoSelect(TabLayout.Tab tab) {
  109. View customView = tab.getCustomView();
  110. TextView tabText = (TextView) customView.findViewById(R.id.item_text);
  111. ImageView tabIcon = (ImageView) customView.findViewById(R.id.item_img);
  112. tabText.setTextColor(ContextCompat.getColor(this, R.color.colorBlack));
  113. String stitle = tabText.getText().toString();
  114. for(int i=0;i<Ltitles.length;i++){
  115. if(Ltitles[i].equals(stitle)){
  116. tabIcon.setImageResource(Limg[i]);
  117. }
  118. }
  119. }
  120.  
  121. }

升级篇

Android Studio3版本:android-studio-ide-191.5900203-windows

依赖修改

  1. implementation 'com.android.support:design:28.0.0'

XML修改:

  1. <!--
  2. app:tabIndicatorColor="" 指示器颜色
  3. app:tabIndicatorHeight="" 指示器高度,设置为0就是没有指示器
  4. app:tabTextColor="" Tab文本默认颜色
  5. app:tabSelectedTextColor="" Tab文本被选中后的颜色
  6. app:tabTextAppearance="" 为Tab文本设置样式,一般是需要为Tab加图标时使用
  7. app:tabMode="" 只有两个值:fixed、scrollable
  8. 其中 fixed用于标题栏少的情况,每个Tab可以平分屏幕宽度
  9. 其中 scrollable用于标题栏多出屏幕的情况,如果标题栏少的时候用很难看,占不满屏幕
  10. app:tabGravity="center" 整体居中,不可与上共用
  11. app:tabBackground="" TabLayout背景,和android:background=""效果一样
  12. app:tabGravity="" 对齐方式: 居中显示center、fill填满
  13. -->
  14.  
  15. <com.google.android.material.tabs.TabLayout
  16. android:id="@+id/tabs2"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:layout_gravity="center"
  20. app:tabMode="fixed"
  21. app:tabIndicatorColor="@color/colorLv"
  22. app:tabTextColor="@android:color/black"
  23. app:tabSelectedTextColor="@color/colorred"
  24. />
  25.  
  26. <androidx.viewpager.widget.ViewPager
  27. android:id="@+id/viewpager"
  28. android:layout_width="match_parent"
  29. android:layout_height="0dp"
  30. android:layout_weight=""
  31. />

导入修改

  1. import com.google.android.material.tabs.TabLayout;
  2. import androidx.viewpager.widget.ViewPager;

安卓TabLayout+ViewPager实现切页的更多相关文章

  1. TabLayout+ViewPager+Fragment制作页卡

    本人很懒,直接上代码了. 布局文件: <?xml version="1.0" encoding="utf-8"?><android.suppo ...

  2. 安卓官方ViewPager与android.support.design.widget.TabLayout双向交互联动切换 。

    该TabLayout的功用,简单的说,就是当用户在该TabLayout的选项卡子item中选择触摸时候,文字和下方的指示器横条滑动指示.android.support.design.widget.Ta ...

  3. TabLayout + ViewPager

    一.实现思路 1.在build.gradle中添加依赖,例如: compile 'com.android.support:support-v4:23.4.0'compile 'com.android. ...

  4. 介绍三个Android支持库控件:TabLayout+ViewPager+RecyclerView

    本文主要介绍如下三个Android支持库控件的配合使用: TabLayout:android.support.design.widget.TabLayout ViewPager:android.sup ...

  5. [置顶] xamarin Tablayout+Viewpager+Fragment顶部导航栏

    最近几天不忙,所以把项目中的顶部导航栏的实现归集一下.android中使用TabLayout+ViewPager+Fragment制作顶部导航非常常见,代码实现也比较简单.当然我这个导航栏是基于xam ...

  6. Android开发之漫漫长途 Fragment番外篇——TabLayout+ViewPager+Fragment

    该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...

  7. ViewPagerWithRecyclerDemo【RecyclerView+ViewPager实现类似TabLayout+ViewPager效果】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 使用RecyclerView+ViewPager实现类似TabLayout+ViewPager效果. 效果图 使用步骤 一.项目组织 ...

  8. 011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

    1.TabLayout介绍 TabLayout提供了一个水平的布局用来展示Tabs,很多应用都有这样的设计,典型的有网易新闻,简书,知乎等.TabLayout就可以很好的完成这一职责,首先TabLay ...

  9. 关于tablayout+viewpager+fragment配合使用的一点记录

    最近在写项目的时候遇到要求使用tablayout和fragment,遇到了这里记录一下大致思路. tablayout是头部可以左右切换的头部控制栏控件,配合viewpager使用,fragment是碎 ...

随机推荐

  1. 行盒(line box)垂直方向的属性详解:从font-size、line-height到vertical-align

    视觉格式化模型 在一个文档中,每个元素都被表示为0.1或多个矩形的盒子.确定这些盒子的尺寸, 属性 --- 像它的颜色,背景,边框方面 --- 和位置是渲染引擎的目标.① 在CSS中,使用标准盒模型描 ...

  2. k8s 安装步骤

    1 安装Docker 1.1 增加中国区镜像 https://registry.docker-cn.com 2 下载安装k8s的镜像的脚本 https://github.com/AliyunConta ...

  3. UWP作业(二)A Mobile App

    看到给出的十个技术主题,我第一反应就是,对于大部分社交软件来讲,运用到全部这些都并不是什么难题,倒不如谈谈我手机里现有的社交软件中,使用时间最短但(you)是(dian)最(bu)好(hao)奇(yo ...

  4. P1081 开车旅行(Not Finish)

    https://www.luogu.org/problemnew/show/P1081

  5. centos7.6 ssh远程链接配置

    1.firewall增加22端口号 增加方式有两种,直接编辑firewall的public.xml增加 vi /etc/firewalld/zones/public.xml 进入后按i健光标移动到zo ...

  6. JS prototype chaining(原型链)整理中······

    初学原型链整理 构造器(constructor).原型(prototype).实例(instance); 每一个构造器都有一个prototype对象,这个prototype对象有一个指针指向该构造器: ...

  7. 可遇不可求的Question之MySql4.0前版本不支持union与批量SQL提交

    批量SQL提交 参考 21.2.6. Connector/NET Connection String Options Reference . Allow Batch true When true, m ...

  8. HDU 2516 斐波那契博弈

    点这里去看题 n为斐波那契数时,先手败,推断方法见算法讲堂 #include<bits/stdc++.h> using namespace std; int main() { ],i,n, ...

  9. git的命令行操作

    1.初始化本地的git仓库git init,代码存放在这里,git会自动对我们的代码进行管理备份. 2.设置用户信息,设置用户名:git config --global user.name " ...

  10. js:函数与变量作用域的提升

    一.要彻底理解JS的作用域和Hoisting,只要记住以下三点即可:      1.所有申明都会被提升到作用域的最顶上      2.同一个变量申明只进行一次,并且因此其他申明都会被忽略      3 ...