zoukankan      html  css  js  c++  java
  • ViewPager + Fragment实现滑动标签页

    ViewPager 结合Fragment实现一个Activity里包含多个可滑动的标签页,每个标签页可以有独立的布局及响应。

    activity_main.xml

    [html] view plaincopy
     
    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.     android:orientation="vertical">  
    7.   
    8.     <LinearLayout   
    9.         android:layout_width="match_parent"  
    10.         android:layout_height="wrap_content"  
    11.         android:orientation="horizontal">  
    12.           
    13.           
    14.         <TextView   
    15.             android:id="@+id/tv_guid1"  
    16.             android:layout_width="wrap_content"  
    17.             android:layout_height="wrap_content"  
    18.             android:layout_weight="1.0"  
    19.             android:gravity="center"  
    20.             android:text="特性1"  
    21.             android:textSize="18sp"/>  
    22.         <TextView    
    23.             android:id="@+id/tv_guid2"    
    24.             android:layout_width="wrap_content"    
    25.             android:layout_height="wrap_content"    
    26.             android:layout_weight="1.0"    
    27.             android:gravity="center"    
    28.             android:text="特性2"     
    29.             android:textSize="18sp"/>    
    30.     
    31.         <TextView    
    32.             android:id="@+id/tv_guid3"    
    33.             android:layout_width="wrap_content"    
    34.             android:layout_height="wrap_content"    
    35.             android:layout_weight="1.0"    
    36.             android:gravity="center"    
    37.             android:text="特性3 "     
    38.             android:textSize="18sp"/>    
    39.     
    40.         <TextView    
    41.             android:id="@+id/tv_guid4"    
    42.             android:layout_width="wrap_content"    
    43.             android:layout_height="wrap_content"    
    44.             android:layout_weight="1.0"    
    45.             android:gravity="center"    
    46.             android:text="特性4"     
    47.             android:textSize="18sp"/>  
    48.     </LinearLayout>  
    49.   
    50.     <ImageView   
    51.         android:id="@+id/cursor"  
    52.         android:layout_width="wrap_content"  
    53.         android:layout_height="wrap_content"  
    54.         android:scaleType="matrix"  
    55.         android:src="@drawable/cursor"/>  
    56.       
    57.     <android.support.v4.view.ViewPager  
    58.         android:id="@+id/viewpager"  
    59.         android:layout_width="fill_parent"  
    60.         android:layout_height="fill_parent"  
    61.         android:flipInterval="30"  
    62.         android:persistentDrawingCache="animation"/>  
    63. </LinearLayout>  


    MainActivity.java

    [java] view plaincopy
     
    1. package com.example.viewpagernfragment;  
    2.   
    3. import java.util.ArrayList;  
    4.   
    5. import android.graphics.BitmapFactory;  
    6. import android.graphics.Matrix;  
    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.view.Menu;  
    14. import android.view.View;  
    15. import android.view.animation.Animation;  
    16. import android.view.animation.TranslateAnimation;  
    17. import android.widget.ImageView;  
    18. import android.widget.TextView;  
    19. import android.widget.Toast;  
    20.   
    21. public class MainActivity extends FragmentActivity {  
    22.     private ViewPager mPager;  
    23.     private ArrayList<Fragment> fragmentList;  
    24.     private ImageView image;  
    25.     private TextView view1, view2, view3, view4;  
    26.     private int currIndex;//当前页卡编号  
    27.     private int bmpW;//横线图片宽度  
    28.     private int offset;//图片移动的偏移量  
    29.   
    30.       
    31.       
    32.     @Override  
    33.     protected void onCreate(Bundle savedInstanceState) {  
    34.         super.onCreate(savedInstanceState);  
    35.         setContentView(R.layout.activity_main);  
    36.           
    37.         InitTextView();  
    38.         InitImage();  
    39.         InitViewPager();  
    40.     }  
    41.       
    42.       
    43.     /* 
    44.      * 初始化标签名 
    45.      */  
    46.     public void InitTextView(){  
    47.         view1 = (TextView)findViewById(R.id.tv_guid1);  
    48.         view2 = (TextView)findViewById(R.id.tv_guid2);  
    49.         view3 = (TextView)findViewById(R.id.tv_guid3);  
    50.         view4 = (TextView)findViewById(R.id.tv_guid4);  
    51.           
    52.         view1.setOnClickListener(new txListener(0));  
    53.         view2.setOnClickListener(new txListener(1));  
    54.         view3.setOnClickListener(new txListener(2));  
    55.         view4.setOnClickListener(new txListener(3));  
    56.     }  
    57.       
    58.       
    59.     public class txListener implements View.OnClickListener{  
    60.         private int index=0;  
    61.           
    62.         public txListener(int i) {  
    63.             index =i;  
    64.         }  
    65.         @Override  
    66.         public void onClick(View v) {  
    67.             // TODO Auto-generated method stub  
    68.             mPager.setCurrentItem(index);  
    69.         }  
    70.     }  
    71.       
    72.       
    73.     /* 
    74.      * 初始化图片的位移像素 
    75.      */  
    76.     public void InitImage(){  
    77.         image = (ImageView)findViewById(R.id.cursor);  
    78.         bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth();  
    79.         DisplayMetrics dm = new DisplayMetrics();  
    80.         getWindowManager().getDefaultDisplay().getMetrics(dm);  
    81.         int screenW = dm.widthPixels;  
    82.         offset = (screenW/4 - bmpW)/2;  
    83.           
    84.         //imgageview设置平移,使下划线平移到初始位置(平移一个offset)  
    85.         Matrix matrix = new Matrix();  
    86.         matrix.postTranslate(offset, 0);  
    87.         image.setImageMatrix(matrix);  
    88.     }  
    89.       
    90.     /* 
    91.      * 初始化ViewPager 
    92.      */  
    93.     public void InitViewPager(){  
    94.         mPager = (ViewPager)findViewById(R.id.viewpager);  
    95.         fragmentList = new ArrayList<Fragment>();  
    96.         Fragment btFragment= new ButtonFragment();  
    97.         Fragment secondFragment = TestFragment.newInstance("this is second fragment");  
    98.         Fragment thirdFragment = TestFragment.newInstance("this is third fragment");  
    99.         Fragment fourthFragment = TestFragment.newInstance("this is fourth fragment");  
    100.         fragmentList.add(btFragment);  
    101.         fragmentList.add(secondFragment);  
    102.         fragmentList.add(thirdFragment);  
    103.         fragmentList.add(fourthFragment);  
    104.           
    105.         //给ViewPager设置适配器  
    106.         mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));  
    107.         mPager.setCurrentItem(0);//设置当前显示标签页为第一页  
    108.         mPager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器  
    109.     }  
    110.   
    111.       
    112.     public class MyOnPageChangeListener implements OnPageChangeListener{  
    113.         private int one = offset *2 +bmpW;//两个相邻页面的偏移量  
    114.           
    115.         @Override  
    116.         public void onPageScrolled(int arg0, float arg1, int arg2) {  
    117.             // TODO Auto-generated method stub  
    118.               
    119.         }  
    120.           
    121.         @Override  
    122.         public void onPageScrollStateChanged(int arg0) {  
    123.             // TODO Auto-generated method stub  
    124.               
    125.         }  
    126.           
    127.         @Override  
    128.         public void onPageSelected(int arg0) {  
    129.             // TODO Auto-generated method stub  
    130.             Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移动画  
    131.             currIndex = arg0;  
    132.             animation.setFillAfter(true);//动画终止时停留在最后一帧,不然会回到没有执行前的状态  
    133.             animation.setDuration(200);//动画持续时间0.2秒  
    134.             image.startAnimation(animation);//是用ImageView来显示动画的  
    135.             int i = currIndex + 1;  
    136.             Toast.makeText(MainActivity.this, "您选择了第"+i+"个页卡", Toast.LENGTH_SHORT).show();  
    137.         }  
    138.     }  
    139.       
    140.       
    141.     @Override  
    142.     public boolean onCreateOptionsMenu(Menu menu) {  
    143.         // Inflate the menu; this adds items to the action bar if it is present.  
    144.         getMenuInflater().inflate(R.menu.main, menu);  
    145.         return true;  
    146.     }  
    147.   
    148. }  

    谷歌官方认为,ViewPager应该和Fragment一起使用时,此时ViewPager的适配器是FragmentPagerAdapter,当你实现一个FragmentPagerAdapter,你必须至少覆盖以下方法:

    getCount()

    getItem()

    如果ViewPager没有和Fragment一起,ViewPager的适配器是PagerAdapter,它是基类提供适配器来填充页面ViewPager内部,当你实现一个PagerAdapter,你必须至少覆盖以下方法:


    [java] view plaincopy
     
    1. package com.example.viewpagernfragment;  
    2.   
    3. import java.util.ArrayList;  
    4.   
    5. import android.support.v4.app.Fragment;  
    6. import android.support.v4.app.FragmentManager;  
    7. import android.support.v4.app.FragmentPagerAdapter;  
    8.   
    9. public class MyFragmentPagerAdapter extends FragmentPagerAdapter{  
    10.     ArrayList<Fragment> list;  
    11.     public MyFragmentPagerAdapter(FragmentManager fm,ArrayList<Fragment> list) {  
    12.         super(fm);  
    13.         this.list = list;  
    14.           
    15.     }  
    16.       
    17.       
    18.     @Override  
    19.     public int getCount() {  
    20.         return list.size();  
    21.     }  
    22.       
    23.     @Override  
    24.     public Fragment getItem(int arg0) {  
    25.         return list.get(arg0);  
    26.     }  
    27.       
    28.       
    29.       
    30.       
    31. }  

    [java] view plaincopy
     
    1. package com.example.viewpagernfragment;  
    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. import android.widget.Button;  
    9. import android.widget.Toast;  
    10.   
    11. public class ButtonFragment extends Fragment{  
    12.     Button myButton;  
    13.       
    14.     @Override  
    15.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
    16.             Bundle savedInstanceState) {  
    17.         View rootView = inflater.inflate(R.layout.guide_1, container, false);//关联布局文件  
    18.           
    19.         myButton = (Button)rootView.findViewById(R.id.mybutton);//根据rootView找到button  
    20.           
    21.         //设置按键监听事件  
    22.         myButton.setOnClickListener(new View.OnClickListener() {  
    23.               
    24.             @Override  
    25.             public void onClick(View v) {  
    26.                 // TODO Auto-generated method stub  
    27.                 Toast.makeText(ButtonFragment.this.getActivity(), "button is click!", Toast.LENGTH_SHORT).show();  
    28.             }  
    29.         });  
    30.           
    31.           
    32.         return rootView;  
    33.     }  
    34. }  

    [java] view plaincopy
     
    1. package com.example.viewpagernfragment;  
    2.   
    3. import android.os.Bundle;  
    4. import android.support.v4.app.Fragment;  
    5. import android.util.Log;  
    6. import android.view.LayoutInflater;  
    7. import android.view.View;  
    8. import android.view.ViewGroup;  
    9. import android.widget.TextView;  
    10.   
    11. public class TestFragment extends Fragment {  
    12.     private static final String TAG = "TestFragment";  
    13.     private String hello;// = "hello android";  
    14.     private String defaultHello = "default value";  
    15.   
    16.     static TestFragment newInstance(String s) {  
    17.         TestFragment newFragment = new TestFragment();  
    18.         Bundle bundle = new Bundle();  
    19.         bundle.putString("hello", s);  
    20.         newFragment.setArguments(bundle);  
    21.           
    22.         //bundle还可以在每个标签里传送数据  
    23.           
    24.           
    25.         return newFragment;  
    26.   
    27.     }  
    28.   
    29.   
    30.   
    31.     @Override  
    32.     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {  
    33.         Log.d(TAG, "TestFragment-----onCreateView");  
    34.         Bundle args = getArguments();  
    35.         hello = args != null ? args.getString("hello") : defaultHello;  
    36.         View view = inflater.inflate(R.layout.guide_2, container, false);  
    37.         TextView viewhello = (TextView) view.findViewById(R.id.tv);  
    38.         viewhello.setText(hello);  
    39.         return view;  
    40.   
    41.     }  
    42.   
    43.      
    44.   
    45. }  

    [html] view plaincopy
     
    1. <?xml version="1.0" encoding="UTF-8"?>    
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    3.     android:layout_width="fill_parent"    
    4.     android:layout_height="fill_parent"    
    5.     android:background="#ff0000ff" >    
    6.       
    7.     <Button   
    8.         android:id="@+id/mybutton"  
    9.         android:layout_width="wrap_content"  
    10.         android:layout_height="wrap_content"  
    11.         android:text="hit me"  
    12.         android:gravity="center"/>  
    13. </RelativeLayout>    

    [html] view plaincopy
     
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="fill_parent"  
    4.     android:layout_height="fill_parent"  
    5.     android:orientation="vertical"  
    6.     android:background="#158684" >  
    7.   
    8.   
    9.     <TextView  
    10.         android:id="@+id/tv"  
    11.         android:layout_width="wrap_content"  
    12.         android:layout_height="wrap_content"  
    13.         android:text="TextView" />  
    14.   
    15. </RelativeLayout>  


  • 相关阅读:
    15 | 二分查找(上):如何用最省内存的方式实现快速查找功能?
    11 | 线程:如何让复杂的项目并行执行?
    数据结构与算法-10-递归调用
    (图文并茂,权威最详细)Wireshark抓包分析 TCP三次握手/四次挥手详解
    总结-自己傻的坑学习java spingboot不仔细
    网络抓包
    数据库简介
    JavaSE基础之Map与Collection
    JavaSE基础之抽象类与接口
    JavaSE基础之重载和重写
  • 原文地址:https://www.cnblogs.com/xgjblog/p/4618786.html
Copyright © 2011-2022 走看看