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

在项目中,我们常常需要实现界面滑动切换的效果。例如,微信界面的左右滑动切换效果。那这种效果是怎么实现的?今天我就带大家简单了解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.   
  7.     <include layout="@layout/activity_main_top_tab" />  
  8.   
  9.     <android.support.v4.view.ViewPager  
  10.         android:id="@+id/id_page_vp"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="0dp"  
  13.         android:layout_weight="1" >  
  14.     </android.support.v4.view.ViewPager>  
  15.   
  16. </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.   
  7.     <LinearLayout  
  8.         android:id="@+id/id_switch_tab_ll"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:orientation="horizontal"   
  12.         android:baselineAligned="false"  
  13.         >  
  14.   
  15.         <LinearLayout  
  16.             android:id="@+id/id_tab_chat_ll"  
  17.             android:layout_width="match_parent"  
  18.             android:layout_height="wrap_content"  
  19.             android:layout_weight="1"  
  20.             android:background="@drawable/guide_round_selector"  
  21.             android:gravity="center"  
  22.             android:orientation="horizontal"  
  23.             android:padding="10dip" >  
  24.   
  25.             <TextView  
  26.                 android:id="@+id/id_chat_tv"  
  27.                 android:layout_width="wrap_content"  
  28.                 android:layout_height="wrap_content"  
  29.                 android:gravity="center"  
  30.                 android:text="聊天"  
  31.                 android:textColor="#0000FF"  
  32.                 android:textSize="15dip" />  
  33.         </LinearLayout>  
  34.   
  35.         <LinearLayout  
  36.             android:id="@+id/id_tab_friend_ll"  
  37.             android:layout_width="match_parent"  
  38.             android:layout_height="wrap_content"  
  39.             android:layout_weight="1"  
  40.             android:background="@drawable/guide_round_selector"  
  41.             android:clickable="true"  
  42.             android:gravity="center"  
  43.             android:orientation="horizontal"  
  44.             android:padding="10dip"  
  45.             android:saveEnabled="false" >  
  46.   
  47.             <TextView  
  48.                 android:id="@+id/id_friend_tv"  
  49.                 android:layout_width="wrap_content"  
  50.                 android:layout_height="wrap_content"  
  51.                 android:gravity="center"  
  52.                 android:text="好友"  
  53.                 android:textColor="#000000"  
  54.                 android:textSize="15dip" />  
  55.         </LinearLayout>  
  56.   
  57.         <LinearLayout  
  58.             android:id="@+id/id_tab_contacts_ll"  
  59.             android:layout_width="match_parent"  
  60.             android:layout_height="wrap_content"  
  61.             android:layout_weight="1"  
  62.             android:background="@drawable/guide_round_selector"  
  63.             android:focusable="false"  
  64.             android:gravity="center"  
  65.             android:orientation="horizontal"  
  66.             android:padding="10dip" >  
  67.   
  68.             <TextView  
  69.                 android:id="@+id/id_contacts_tv"  
  70.                 android:layout_width="wrap_content"  
  71.                 android:layout_height="wrap_content"  
  72.                 android:gravity="center"  
  73.                 android:text="通讯录"  
  74.                 android:textColor="#000000"  
  75.                 android:textSize="15dip" />  
  76.         </LinearLayout>  
  77.     </LinearLayout>  
  78.   
  79.     <ImageView  
  80.         android:id="@+id/id_tab_line_iv"  
  81.         android:layout_width="200dp"  
  82.         android:layout_height="wrap_content"  
  83.         android:contentDescription="tab"  
  84.         android:background="@drawable/tab_selected_pressed_holo" >  
  85.     </ImageView>  
  86.   
  87.     <View  
  88.         android:layout_width="match_parent"  
  89.         android:layout_height="1dp"  
  90.         android:background="#000000" />  
  91.   
  92. </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.   
  7.     <TextView  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="match_parent"  
  10.         android:text="聊天界面"  
  11.         android:textColor="#FF0000"  
  12.         android:textSize="20sp"  
  13.         android:gravity="center"  
  14.         ></TextView>  
  15.   
  16. </LinearLayout></span>  
4>主函数MainActivity.java

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

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

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

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值