在这里主要运用到的是ViewPager和TabLayout。
首先展示效果图
简单介绍下ViewPager
ViewPager和ListView很相似都要使用到Adapter。ViewPager中有三种Adapter:
- PagerAdapter
- FragmentPager
- FragmentStatePagerAdapter
在实现PagerAdapter的过程中要求至少覆盖以下几个方法:
- instantiateItem
- destroyItem
- getCount
- isViewFromObject
ViewPager不直接处理每个视图而是将各个视图与一个 键联系起来,每个键用来更重视图且唯一代表一个视图,isViewFromObject就是用来判断键与视图是否匹配。
三种适配器的区别
- PagerAdapter是基类适配器,是一个通用的ViewPager适配器。
- FragmentPageAdapter和FragmentStatePagerAdapter更专注于每一页是Fragment的情况。
FragmentPagerAdapter适用于页面较少情况,因为它在destroyItem中并没有真正释放Fragment而是detach,虽然消耗内存但是效率高。FragmentStatePagerAdapter在destroyItem中有真正释放,会更省内存。
更详细的介绍查看这个链接http://blog.csdn.net/harvic880925/article/details/38453725
开始进入正题
要使用TabLayout需要在gradle中加入下面内容
compile 'com.android.support:design:25.3.1'
往activity_main.xml中添加布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorGreen"
android:orientation="horizontal">
<TextView
android:id="@+id/text_login"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center|left"
android:paddingLeft="10dp"
android:text="登录"
android:textColor="@color/textWhite"
android:textSize="20sp" />
<TextView
android:id="@+id/text_register"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center|right"
android:paddingRight="10dp"
android:text="注册"
android:textColor="@color/textWhite"
android:textSize="20sp" />
</LinearLayout>
<android.support.design.widget.TabLayout
android:id="@+id/tab_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorGreen"
app:tabSelectedTextColor="@color/colorGreen">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
</android.support.v4.view.ViewPager>
</LinearLayout>
这里的主要代码就是,其中tabIndicatorColor是用来设置TabLayout下方滑动条的颜色,tabSelectedTextColor是用来设置被选择后显示的颜色。
<android.support.design