Android ViewPager多页面滑动切换以及动画效果

来源:互联网 发布:网络的碳足迹是什么 编辑:程序博客网 时间:2024/05/16 05:31

一、首先,我们来看一下效果图,这是新浪微博的Tab滑动效果。我们可以手势滑动,也可以点击上面的头标进行切换。与此同方式,

白色横条会移动到相应的页卡头标下。这是一个动画效果,白条是缓慢滑动过去的。好了,接下来我们就来实现它。

 

二、在开始前,我们先要认识一个控件,ViewPager。它是google SDk中自带的一个附加包的一个类,可以用来实现屏幕间的切换。

这个附加包是android-support-v4.jar,在最后的源码中会提供给大家,在libs文件夹中。当然你也可以自己从网上搜索最新的版本。

找到它后,我们需要在项目中添加

 

三、我们先做界面,

界面设计很简单,第一行三个头标,第二行动画图片,第三行页卡内容展示。

复制代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:umadsdk="http://schemas.android.com/apk/res/com.LoveBus"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="fill_parent"        android:layout_height="100.0dip"        android:background="#FFFFFF" >        <TextView            android:id="@+id/text1"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:layout_weight="1.0"            android:gravity="center"            android:text="页卡1"            android:textColor="#000000"            android:textSize="22.0dip" />        <TextView            android:id="@+id/text2"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:layout_weight="1.0"            android:gravity="center"            android:text="页卡2"            android:textColor="#000000"            android:textSize="22.0dip" />        <TextView            android:id="@+id/text3"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:layout_weight="1.0"            android:gravity="center"            android:text="页卡3"            android:textColor="#000000"            android:textSize="22.0dip" />    </LinearLayout>    <ImageView        android:id="@+id/cursor"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:scaleType="matrix"        android:src="@drawable/a" />    <android.support.v4.view.ViewPager        android:id="@+id/vPager"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_weight="1.0"        android:background="#000000"        android:flipInterval="30"        android:persistentDrawingCache="animation" /></LinearLayout>
复制代码


 

我们要展示三个页卡,所以还需要三个页卡内容的界面设计,这里我们只设置了背景颜色,能起到区别作用即可。

复制代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:background="#158684" ></LinearLayout>
复制代码

 

四、代码部分要进行初始化的工作

(1) 先来变量的定义

复制代码
    private ViewPager mPager;//页卡内容    private List<View> listViews; // Tab页面列表    private ImageView cursor;// 动画图片    private TextView t1, t2, t3;// 页卡头标    private int offset = 0;// 动画图片偏移量    private int currIndex = 0;// 当前页卡编号    private int bmpW;// 动画图片宽度
复制代码

 

(2) 初始化头标

复制代码
 1     /** 2      * 初始化头标 3 */ 4     private void InitTextView() { 5         t1 = (TextView) findViewById(R.id.text1); 6         t2 = (TextView) findViewById(R.id.text2); 7         t3 = (TextView) findViewById(R.id.text3); 8  9         t1.setOnClickListener(new MyOnClickListener(0));10         t2.setOnClickListener(new MyOnClickListener(1));11         t3.setOnClickListener(new MyOnClickListener(2));12     }
复制代码
复制代码
 1     /** 2      * 头标点击监听 3 */ 4     public class MyOnClickListener implements View.OnClickListener { 5         private int index = 0; 6  7         public MyOnClickListener(int i) { 8             index = i; 9         }10 11         @Override12         public void onClick(View v) {13             mPager.setCurrentItem(index);14         }15     };
复制代码

相信大家看后都没什么问题,点击第几个,就展示第几个页卡内容。

 

(3) 初始化页卡内容区

复制代码
 1     /** 2      * 初始化ViewPager 3 */ 4     private void InitViewPager() { 5         mPager = (ViewPager) findViewById(R.id.vPager); 6         listViews = new ArrayList<View>(); 7         LayoutInflater mInflater = getLayoutInflater(); 8         listViews.add(mInflater.inflate(R.layout.lay1, null)); 9         listViews.add(mInflater.inflate(R.layout.lay2, null));10         listViews.add(mInflater.inflate(R.layout.lay3, null));11         mPager.setAdapter(new MyPagerAdapter(listViews));12         mPager.setCurrentItem(0);13         mPager.setOnPageChangeListener(new MyOnPageChangeListener());14     }
复制代码

我们将三个页卡界面装入其中,默认显示第一个页卡。这里我们还需要实现一个适配器。

复制代码
 1 /** 2      * ViewPager适配器 3 */ 4     public class MyPagerAdapter extends PagerAdapter { 5         public List<View> mListViews; 6  7         public MyPagerAdapter(List<View> mListViews) { 8             this.mListViews = mListViews; 9         }10 11         @Override12         public void destroyItem(View arg0, int arg1, Object arg2) {13             ((ViewPager) arg0).removeView(mListViews.get(arg1));14         }15 16         @Override17         public void finishUpdate(View arg0) {18         }19 20         @Override21         public int getCount() {22             return mListViews.size();23         }24 25         @Override26         public Object instantiateItem(View arg0, int arg1) {27             ((ViewPager) arg0).addView(mListViews.get(arg1), 0);28             return mListViews.get(arg1);29         }30 31         @Override32         public boolean isViewFromObject(View arg0, Object arg1) {33             return arg0 == (arg1);34         }35 36         @Override37         public void restoreState(Parcelable arg0, ClassLoader arg1) {38         }39 40         @Override41         public Parcelable saveState() {42             return null;43         }44 45         @Override46         public void startUpdate(View arg0) {47         }48     }
复制代码

这里我们实现了各页卡的装入和卸载

 

(3) 初始化动画

复制代码
 1     /** 2      * 初始化动画 3 */ 4     private void InitImageView() { 5         cursor = (ImageView) findViewById(R.id.cursor); 6         bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a) 7                 .getWidth();// 获取图片宽度 8         DisplayMetrics dm = new DisplayMetrics(); 9         getWindowManager().getDefaultDisplay().getMetrics(dm);10         int screenW = dm.widthPixels;// 获取分辨率宽度11         offset = (screenW / 3 - bmpW) / 2;// 计算偏移量12         Matrix matrix = new Matrix();13         matrix.postTranslate(offset, 0);14         cursor.setImageMatrix(matrix);// 设置动画初始位置15     }
复制代码

根据屏幕的分辨率和图片的宽度计算动画移动的偏移量

实现页卡切换监听

复制代码
 1 /** 2      * 页卡切换监听 3 */ 4     public class MyOnPageChangeListener implements OnPageChangeListener { 5  6         int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量 7         int two = one * 2;// 页卡1 -> 页卡3 偏移量 8  9         @Override10         public void onPageSelected(int arg0) {11             Animation animation = null;12             switch (arg0) {13             case 0:14                 if (currIndex == 1) {15                     animation = new TranslateAnimation(one, 0, 0, 0);16                 } else if (currIndex == 2) {17                     animation = new TranslateAnimation(two, 0, 0, 0);18                 }19                 break;20             case 1:21                 if (currIndex == 0) {22                     animation = new TranslateAnimation(offset, one, 0, 0);23                 } else if (currIndex == 2) {24                     animation = new TranslateAnimation(two, one, 0, 0);25                 }26                 break;27             case 2:28                 if (currIndex == 0) {29                     animation = new TranslateAnimation(offset, two, 0, 0);30                 } else if (currIndex == 1) {31                     animation = new TranslateAnimation(one, two, 0, 0);32                 }33                 break;34             }35             currIndex = arg0;36             animation.setFillAfter(true);// True:图片停在动画结束位置37             animation.setDuration(300);38             cursor.startAnimation(animation);39         }40 41         @Override42         public void onPageScrolled(int arg0, float arg1, int arg2) {43         }44 45         @Override46         public void onPageScrollStateChanged(int arg0) {47         }48     }
复制代码

 

五、打完收工,快来看看自己的劳动成果吧


很多人问到页卡内添加事件的问题,开始没写进去,现在补。

 

一、页卡1内添加一个测试按钮。

复制代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    android:background="#158684" >    <Button        android:id="@+id/btn"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:gravity="center"        android:text="事件测试" /></LinearLayout>
复制代码

 

二、在适配器的初始化方法中添加按钮事件,这里是关键,首先判断当前的页卡编号。必须使用当前的view来获取按钮。

复制代码
        @Override        public Object instantiateItem(View arg0, int arg1) {            if (arg1 < 3) {                ((ViewPager) arg0).addView(mListViews.get(arg1 % 3), 0);            }            // 测试页卡1内的按钮事件            if (arg1 == 0) {                Button btn = (Button) arg0.findViewById(R.id.btn);                btn.setOnClickListener(new View.OnClickListener() {                    @Override                    public void onClick(View v) {                        new AlertDialog.Builder(MainActivity.this)                                .setTitle("说明")                                .setMessage("单个页卡内按钮事件测试")                                .setNegativeButton("确定",                                        new DialogInterface.OnClickListener() {                                            @Override                                            public void onClick(                                                    DialogInterface dialog,                                                    int which) {                                            }                                        }).show();                    }                });            }            return mListViews.get(arg1 % 3);        }
复制代码

作者:D.Winter 
个人网站:http://www.dwintergame.com/ 
广告平台:传送门
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 

原文地址:  http://www.cnblogs.com/dwinter/archive/2012/02/27/2369590.html 和 http://www.cnblogs.com/dwinter/archive/2012/07/06/2579112.html

原创粉丝点击