在项目中,我们常常需要实现界面滑动切换的效果。例如,微信界面的左右滑动切换效果。那这种效果是怎么实现的?今天我就带大家简单了解ViewPager,并通过实例来实现该效果。

一. ViewPager 官方API

首先我们来看一下ViewPager官方给出的解释,如图:

具体意思如下:

Layout 管理器允许用户可以在页面上,左右滑动来翻动页面。你可以考虑实现PagerAdapter接口来显示该效果。

ViewPager很多时候会结合Fragment一块使用,这种方法使得管理每个页面的生命周期变得很方便。其中,有一些adapter的具体实现,可以适合于这种ViewPager结合Fragment使用的情况。这些adapter包括:FragmentPagerAdapter,和 FragmentStatePagerAdapter。

而本文就是通过ViewPager结合Fragment利用FragmentpagerAdapter适配器来实现左右滑动的效果。

二.效果如下:

三.代码实现:

1.xml布局文件

1>主布局activity_main.xml

  1. <span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <include layout="@layout/activity_main_top_tab" />
  7. <android.support.v4.view.ViewPager
  8. android:id="@+id/id_page_vp"
  9. android:layout_width="match_parent"
  10. android:layout_height="0dp"
  11. android:layout_weight="1" >
  12. </android.support.v4.view.ViewPager>
  13. </LinearLayout></span>

注意:布局中加载android.support.v4.view.ViewPager,所有需要引入android-support-v4.jar(正常情况系统会自动引入)

2>顶部导航activity_main_top_tab.xml

  1. <span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:id="@+id/id_switch_tab_ll"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:orientation="horizontal"
  11. android:baselineAligned="false"
  12. >
  13. <LinearLayout
  14. android:id="@+id/id_tab_chat_ll"
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:layout_weight="1"
  18. android:background="@drawable/guide_round_selector"
  19. android:gravity="center"
  20. android:orientation="horizontal"
  21. android:padding="10dip" >
  22. <TextView
  23. android:id="@+id/id_chat_tv"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:gravity="center"
  27. android:text="聊天"
  28. android:textColor="#0000FF"
  29. android:textSize="15dip" />
  30. </LinearLayout>
  31. <LinearLayout
  32. android:id="@+id/id_tab_friend_ll"
  33. android:layout_width="match_parent"
  34. android:layout_height="wrap_content"
  35. android:layout_weight="1"
  36. android:background="@drawable/guide_round_selector"
  37. android:clickable="true"
  38. android:gravity="center"
  39. android:orientation="horizontal"
  40. android:padding="10dip"
  41. android:saveEnabled="false" >
  42. <TextView
  43. android:id="@+id/id_friend_tv"
  44. android:layout_width="wrap_content"
  45. android:layout_height="wrap_content"
  46. android:gravity="center"
  47. android:text="好友"
  48. android:textColor="#000000"
  49. android:textSize="15dip" />
  50. </LinearLayout>
  51. <LinearLayout
  52. android:id="@+id/id_tab_contacts_ll"
  53. android:layout_width="match_parent"
  54. android:layout_height="wrap_content"
  55. android:layout_weight="1"
  56. android:background="@drawable/guide_round_selector"
  57. android:focusable="false"
  58. android:gravity="center"
  59. android:orientation="horizontal"
  60. android:padding="10dip" >
  61. <TextView
  62. android:id="@+id/id_contacts_tv"
  63. android:layout_width="wrap_content"
  64. android:layout_height="wrap_content"
  65. android:gravity="center"
  66. android:text="通讯录"
  67. android:textColor="#000000"
  68. android:textSize="15dip" />
  69. </LinearLayout>
  70. </LinearLayout>
  71. <ImageView
  72. android:id="@+id/id_tab_line_iv"
  73. android:layout_width="200dp"
  74. android:layout_height="wrap_content"
  75. android:contentDescription="tab"
  76. android:background="@drawable/tab_selected_pressed_holo" >
  77. </ImageView>
  78. <View
  79. android:layout_width="match_parent"
  80. android:layout_height="1dp"
  81. android:background="#000000" />
  82. </LinearLayout></span>

3>Fragment显示布局activity_tab_chat.xml,activity_tab_contacts.xml,activity_tab_friend.xml(只给出一个,其他类似)

  1. <span style="font-family:Microsoft YaHei;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent"
  9. android:text="聊天界面"
  10. android:textColor="#FF0000"
  11. android:textSize="20sp"
  12. android:gravity="center"
  13. ></TextView>
  14. </LinearLayout></span>

4>主函数MainActivity.java

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">package com.example.viewpagerdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.graphics.Color;
  5. import android.os.Bundle;
  6. import android.support.v4.app.Fragment;
  7. import android.support.v4.app.FragmentActivity;
  8. import android.support.v4.view.ViewPager;
  9. import android.support.v4.view.ViewPager.OnPageChangeListener;
  10. import android.util.DisplayMetrics;
  11. import android.util.Log;
  12. import android.widget.ImageView;
  13. import android.widget.LinearLayout;
  14. import android.widget.TextView;
  15. public class MainActivity extends FragmentActivity {
  16. private List<Fragment> mFragmentList = new ArrayList<Fragment>();
  17. private FragmentAdapter mFragmentAdapter;
  18. private ViewPager mPageVp;
  19. /**
  20. * Tab显示内容TextView
  21. */
  22. private TextView mTabChatTv, mTabContactsTv, mTabFriendTv;
  23. /**
  24. * Tab的那个引导线
  25. */
  26. private ImageView mTabLineIv;
  27. /**
  28. * Fragment
  29. */
  30. private ChatFragment mChatFg;
  31. private FriendFragment mFriendFg;
  32. private ContactsFragment mContactsFg;
  33. /**
  34. * ViewPager的当前选中页
  35. */
  36. private int currentIndex;
  37. /**
  38. * 屏幕的宽度
  39. */
  40. private int screenWidth;
  41. @Override
  42. protected void onCreate(Bundle savedInstanceState) {
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.activity_main);
  45. findById();
  46. init();
  47. initTabLineWidth();
  48. }
  49. private void findById() {
  50. mTabContactsTv = (TextView) this.findViewById(R.id.id_contacts_tv);
  51. mTabChatTv = (TextView) this.findViewById(R.id.id_chat_tv);
  52. mTabFriendTv = (TextView) this.findViewById(R.id.id_friend_tv);
  53. mTabLineIv = (ImageView) this.findViewById(R.id.id_tab_line_iv);
  54. mPageVp = (ViewPager) this.findViewById(R.id.id_page_vp);
  55. }
  56. private void init() {
  57. mFriendFg = new FriendFragment();
  58. mContactsFg = new ContactsFragment();
  59. mChatFg = new ChatFragment();
  60. mFragmentList.add(mChatFg);
  61. mFragmentList.add(mFriendFg);
  62. mFragmentList.add(mContactsFg);
  63. mFragmentAdapter = new FragmentAdapter(
  64. this.getSupportFragmentManager(), mFragmentList);
  65. mPageVp.setAdapter(mFragmentAdapter);
  66. mPageVp.setCurrentItem(0);
  67. mPageVp.setOnPageChangeListener(new OnPageChangeListener() {
  68. /**
  69. * state滑动中的状态 有三种状态(0,1,2) 1:正在滑动 2:滑动完毕 0:什么都没做。
  70. */
  71. @Override
  72. public void onPageScrollStateChanged(int state) {
  73. }
  74. /**
  75. * position :当前页面,及你点击滑动的页面 offset:当前页面偏移的百分比
  76. * offsetPixels:当前页面偏移的像素位置
  77. */
  78. @Override
  79. public void onPageScrolled(int position, float offset,
  80. int offsetPixels) {
  81. LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
  82. .getLayoutParams();
  83. Log.e("offset:", offset + "");
  84. /**
  85. * 利用currentIndex(当前所在页面)和position(下一个页面)以及offset来
  86. * 设置mTabLineIv的左边距 滑动场景:
  87. * 记3个页面,
  88. * 从左到右分别为0,1,2
  89. * 0->1; 1->2; 2->1; 1->0
  90. */
  91. if (currentIndex == 0 && position == 0)// 0->1
  92. {
  93. lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 3) + currentIndex
  94. * (screenWidth / 3));
  95. } else if (currentIndex == 1 && position == 0) // 1->0
  96. {
  97. lp.leftMargin = (int) (-(1 - offset)
  98. * (screenWidth * 1.0 / 3) + currentIndex
  99. * (screenWidth / 3));
  100. } else if (currentIndex == 1 && position == 1) // 1->2
  101. {
  102. lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 3) + currentIndex
  103. * (screenWidth / 3));
  104. } else if (currentIndex == 2 && position == 1) // 2->1
  105. {
  106. lp.leftMargin = (int) (-(1 - offset)
  107. * (screenWidth * 1.0 / 3) + currentIndex
  108. * (screenWidth / 3));
  109. }
  110. mTabLineIv.setLayoutParams(lp);
  111. }
  112. @Override
  113. public void onPageSelected(int position) {
  114. resetTextView();
  115. switch (position) {
  116. case 0:
  117. mTabChatTv.setTextColor(Color.BLUE);
  118. break;
  119. case 1:
  120. mTabFriendTv.setTextColor(Color.BLUE);
  121. break;
  122. case 2:
  123. mTabContactsTv.setTextColor(Color.BLUE);
  124. break;
  125. }
  126. currentIndex = position;
  127. }
  128. });
  129. }
  130. /**
  131. * 设置滑动条的宽度为屏幕的1/3(根据Tab的个数而定)
  132. */
  133. private void initTabLineWidth() {
  134. DisplayMetrics dpMetrics = new DisplayMetrics();
  135. getWindow().getWindowManager().getDefaultDisplay()
  136. .getMetrics(dpMetrics);
  137. screenWidth = dpMetrics.widthPixels;
  138. LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv
  139. .getLayoutParams();
  140. lp.width = screenWidth / 3;
  141. mTabLineIv.setLayoutParams(lp);
  142. }
  143. /**
  144. * 重置颜色
  145. */
  146. private void resetTextView() {
  147. mTabChatTv.setTextColor(Color.BLACK);
  148. mTabFriendTv.setTextColor(Color.BLACK);
  149. mTabContactsTv.setTextColor(Color.BLACK);
  150. }
  151. }
  152. </span>

注意:

1.MainActivity继承于FragmentActivity;

2.初始化导航条的宽度:initTabLineWidth(),由于本例给出的是3个界面切换,固长度为整个屏幕宽度的1/3;

3.监听事件OnPageChangeListener的onPageScrolled方法主要捕捉滑动事件;

其中给出了3个参数所表示的意义。根据滑动的4中变化(左-中-右-中-左),给出导航条距离左边的边距,显示导航条滑动的效果。

5>Fragment适配器FragmentAdapter,继承于FragmentPagerAdapter

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">package com.example.viewpagerdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v4.app.FragmentManager;
  6. import android.support.v4.app.FragmentPagerAdapter;
  7. public class FragmentAdapter extends FragmentPagerAdapter {
  8. List<Fragment> fragmentList = new ArrayList<Fragment>();
  9. public FragmentAdapter(FragmentManager fm,List<Fragment> fragmentList) {
  10. super(fm);
  11. this.fragmentList = fragmentList;
  12. }
  13. @Override
  14. public Fragment getItem(int position) {
  15. return fragmentList.get(position);
  16. }
  17. @Override
  18. public int getCount() {
  19. return fragmentList.size();
  20. }
  21. }
  22. </span>

6>Fragment显示函数ChatFragment.java,ContactsFragment.java,FriendFragment.java(只给出一个,其他类似)

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">package com.example.viewpagerdemo;
  2. import android.os.Bundle;
  3. import android.support.v4.app.Fragment;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. public class ChatFragment extends Fragment {
  8. @Override
  9. public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
  10. super.onCreateView(inflater, container, savedInstanceState);
  11. View chatView = inflater.inflate(R.layout.activity_tab_chat, container,false);
  12. return chatView;
  13. }
  14. @Override
  15. public void onActivityCreated(Bundle savedInstanceState){
  16. super.onActivityCreated(savedInstanceState);
  17. }
  18. }
  19. </span>

上面就是本文的所有内容。

Android ViewPager和Fragment实现顶部导航界面滑动效果相关推荐

  1. Android 应用开发----7. ViewPager+Fragment一步步打造顶部导航界面滑动效果

    ViewPager+Fragment一步步打造顶部导航界面滑动效果 在许多应用中,我们常常用到这么一个效果: 可以看到,由于现在的应用数据经常需要涉及到多个模块,所以常常需要使用滑动标签在多个页面之间 ...

  2. boss直聘Android找工作界面,Android仿Boss直聘我的界面滑动效果

    最近在找工作,我在使用boss投简历的时候,看到boss的我的界面蛮有意思的,就想如何去实现它,可能是职业病吧,所以就打算仿一下.先看下仿的效果. image 其实我们拿到这个效果的时候,看到滑动,折 ...

  3. android viewpager标题,ViewPager顶部导航栏联动效果(标题栏条目多)

    如果标题栏过多,超过屏幕的宽度,该怎么弄,下面我们就来解决一下,效果如下: 其实和之前写的也差不多,我就是在哪个demo里面添加和修改了一下,就加了几个title标题,加了几个图片,最重要的是给Tab ...

  4. Android开发之ViewPager+ActionBar+Fragment实现响应式可滑动Tab

    今天我们要实现的这个效果呢,在Android的应用中十分地常见,我们可以看到下面两张图,无论是系统内置的联系人应用,还是AnyView的阅读器应用,我们总能找到这样的影子,当我们滑动屏幕时,Tab可以 ...

  5. android+qq底部界面,Android 高仿QQ 界面滑动效果

    Android高仿QQ界面滑动效果 点击或者滑动切换画面,用ViewPager实现, 首先是布局文件: android:layout_width="match_parent" an ...

  6. ViewPager、Fragment和TabLayout实现切页效果

    文章目录 ViewPager.Fragment和TabLayout实现切页效果 ViewPager.Fragment和TabLayout实现切页效果 不会上传动图,心里哭唧唧.但是是完整代码!新建一个 ...

  7. Android学QQ空间相册浏览类型横向滑动效果显示多图片MyHorizontalScrollView

    Android学QQ空间相册浏览类型横向滑动效果显示多图片MyHorizontalScrollView 我们来定制一下吧 布局文件:activity_main.xml <LinearLayout ...

  8. android viewpager 嵌套fragment,Android ViewPager+Fragment多层嵌套(使用问题处理)

    之前写了Android ViewPager+Fragment(使用问题处理),封装了一个BaseFragment,对于简单使用ViewPager+Fragment而言,是没有问题的. 不过,ViewP ...

  9. 关于Android ViewPager 与 Fragment 一起使用碰到的问题

    2019独角兽企业重金招聘Python工程师标准>>> 这是我前段时间遇到的两个问题,情况是这样的:第一个问题:由于公司的 app 层级比较多,所以用了一个翻页的功能.在具体翻到某一 ...

最新文章

  1. 关于HttpClient上传中文乱码的解决办法
  2. 深度神经网络中的局部响应归一化LRN简介及实现
  3. JDK1.5 新特性
  4. 实践--课程表(仿超级课程表展示课表)
  5. 在OpenWrt中上传文件至路由器
  6. struts2标签集
  7. strace oracle
  8. 牛客 - Animal Protection(单调栈)
  9. Windows下Android开发环境搭建和配置
  10. Bitmap缩放(二)
  11. MySQL更新死锁问题
  12. 远程桌面计算机正在使用,远程桌面使用问题
  13. 【推荐】区块链技术及行业应用资料合集
  14. Flash actionscrip视频教程
  15. 你的朋友国庆假期都去了哪里玩?微信大数据告诉你!最远的朋友圈签到竟然来自……
  16. SN74LS00N芯片逻辑输出电平
  17. html5分镜头脚本范例,分镜头脚本教程图解
  18. 前Vertu设计师推出Android版iBeacon,无需专有硬件,没话费的旧手机都能做基站
  19. [mysql语法错误]--Cannot load connection class because of underlying exception
  20. [转]我们这么努力,也不过是为了成为一个普通人。

热门文章

  1. [Spring cloud 一步步实现广告系统] 15. 使用开源组件监听Binlog 实现增量索引准备...
  2. [Spring cloud 一步步实现广告系统] 10. 使用Ribbon 实现微服务调用
  3. Java基础23-集合类2(Set接口,Iterator迭代器)
  4. 【Redis】Redis学习(三) Redis 主从模式详解
  5. iOS深入探索直播推拉流实现流程(二:推流权限判断 )
  6. Data Mining Tools
  7. Delphi FastReport动态加载图片
  8. Oracle 不同用户之间 大量数据转移的方法测试
  9. 使用 Eigen 库写第一个程序
  10. 使用 github 和 jitpack 构建 android 依赖