安卓TabLayout+ViewPager实现切页

 

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

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

 

一、实现效果:

 

 

二、实现过程:

2.1 一些重要的设置

 添加必须依赖:

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

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 
11         tabLayout = (TabLayout) findViewById(R.id.tabs2);
12         viewPager = (ViewPager) findViewById(R.id.viewpager);
13 
14         //设置界面文件和文字一一对应
15         final Fragment[] fragments = {new Fragment0(), new Fragment1(), new Fragment2()};
16         final String[] titles = {"界面1", "界面2", "界面3"};
17 
18  //添加tablayout中的竖线,每一项的中间分隔线
19  //LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
20 // linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
21 // linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.mipmap.fg));
22 
23  //每项只进入一次
24  viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
25      @Override
26      public Fragment getItem(int position) {
27          return fragments[position];
28      }
29      @Override
30      public int getCount() {
31          return fragments.length;
32      }
33 
34      @Override
35      public CharSequence getPageTitle(int position) {
36          return titles[position];
37      }
38  });
39 
40  tabLayout.setupWithViewPager(viewPager);
41  tabLayout.getTabAt(1).select();//设置第一个为选中
42     }
43 }

 

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

依赖修改

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="1"
31         />

导入修改

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

 

posted @ 2019-01-03 10:28  东小东  阅读(13012)  评论(2编辑  收藏  举报