ViewPager与ViewFlipper实现图片导航的左右滑动

使用ViewPager和ViewFlipper实现图片导航的左右滑动

效果如下:



1.ViewFlipper控件,是ImageView的容器,用于添加显示的图片资源,主要功能有两个:添加显示View和自动播放View

(1)ViewFlipperActivity

package com.example.navigationimgslide;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * @author zw
 * @deprecated viewFlipper方式
 *
 */

public class ViewFlipperActivity extends Activity implements View.OnTouchListener{

    private MyViewFlipper viewFlipper;
    private LinearLayout lvlayout;
    private GestureDetector mDetector;//手势检测
    private int[] str=new int[]{
            R.drawable.image01,R.drawable.image02,
            R.drawable.image03,R.drawable.image04};

    private ImageView[] images;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewflipper);
        initView();

    }
    /**
     * 初始化
     */
    private void initView(){
        viewFlipper= (MyViewFlipper) findViewById(R.id.viewFlipper);
        lvlayout= (LinearLayout) findViewById(R.id.linear);
        initData();


    }

    private void initData() {

        images=new ImageView[str.length];
        for (int i=1;i<=4;i++){
            viewFlipper.addView(getImageView(str[i-1]));
            img=new ImageView(this);
//           
            //默认选中第一张
            if (i==1){
                img.setImageResource(R.drawable.page);
            }else{
                img.setImageResource(R.drawable.page_now);
            }

            LinearLayout.LayoutParams params= new LinearLayout.LayoutParams( 20,20);
            params.setMargins(10,0,10,0);
            lvlayout.addView(img,params);
        }


        viewFlipper.setOnViewCountListener(new MyViewFlipper.OnViewCountListener() {
            @Override
            public void viewCount(int count) {

                ImageView imgView=null;
                for (int i=0;i<lvlayout.getChildCount();i++){
                    imgView= (ImageView) lvlayout.getChildAt(i);
                    //设置选中的
                    if (count==i){
                        imgView.setImageResource(R.drawable.page);
                    }else{
                       imgView.setImageResource(R.drawable.page_now);
                    }
                }
            }
        });
        viewFlipper.setOnTouchListener(this);

        mDetector=new GestureDetector(new MyGesturListener());

    }

    private View getImageView(int id) {
        ImageView image=new ImageView(this);
        image.setScaleType(ImageView.ScaleType.FIT_XY);
        image.setImageResource(id);
        return image;
    }


    /**
     * 触摸事件
     * @param view
     * @param motionEvent
     * @return
     */
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        // 需要通过手势识别器 去识别触摸的动作
        mDetector.onTouchEvent(motionEvent);
        return true;
    }


    /**
     * 手势识别的监听
     */
    private class MyGesturListener implements GestureDetector.OnGestureListener {

        final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
        @Override
        public boolean onDown(MotionEvent motionEvent) {
            Toast.makeText(ViewFlipperActivity.this,"onDown",Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) {
            Toast.makeText(ViewFlipperActivity.this,"onShowPress",Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            Toast.makeText(ViewFlipperActivity.this,"onSingleTapUp",Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1,
                                float v, float v1) {
            Toast.makeText(ViewFlipperActivity.this,"onScroll",Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public void onLongPress(MotionEvent motionEvent) {
            Toast.makeText(ViewFlipperActivity.this,"onLongPress",Toast.LENGTH_SHORT).show();
        }

        /**
         * 手指滑动屏幕的时候 调用的方法
         * @param e1 是第一触摸屏幕时候的事件
         * @param e2 手指离开时候 的事件
         * @param velocityX x方向的速度
         * @param velocityY y方向的速度
         * @return
         */
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2,
                               float velocityX, float velocityY) {
            Toast.makeText(ViewFlipperActivity.this,"onFling",Toast.LENGTH_SHORT).show();
            //如果垂直方向移动的距离过大 就是无效的手势
            if(Math.abs(e1.getY()-e2.getY()) >FLING_MIN_DISTANCE) {
                return false;

            }

            //判断向右滑动屏幕的事件
            if (e2.getX()-e1.getX()>100 && Math.abs(velocityX)> 100){

                // 指定下一个view对象进来时候的动画效果
                viewFlipper.setInAnimation(ViewFlipperActivity.this,R.anim.in_leftright);

                //设置当前view对象出去时候的动画效果
                viewFlipper.setOutAnimation(ViewFlipperActivity.this,R.anim.out_leftright);

                //显示上一个内容
                viewFlipper.showPrevious();
            }

            //判断向左滑动屏幕的事件
            if (e1.getX()-e2.getX()>100 && Math.abs(velocityX)> 100){

                // 指定下一个view对象进来时候的动画效果
                viewFlipper.setInAnimation(ViewFlipperActivity.this,R.anim.in_rightleft);

                //设置当前view对象出去时候的动画效果
                viewFlipper.setOutAnimation(ViewFlipperActivity.this,R.anim.out_rightleft);

                //显示下一个内容
                viewFlipper.showNext();
            }


            return true;
        }

    }
}

(2)activity_viewFlipper.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="240dp"
    >

    <com.example.navigationimgslide.MyViewFlipper
        android:id="@+id/viewFlipper"
        android:layout_width="match_parent"
        android:layout_height="240dp"
         />


    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:background="#4ccc"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" />


</RelativeLayout>

(3)左右滑动的动画

(3.1)向右滑动屏幕:进、出两个动画
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="2000"
        android:fromXDelta="-100%p"
        android:toXDelta="0"/>
</set>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="2000"
        android:fromXDelta="0"
        android:toXDelta="100%p"/>
</set>

(3.2)向左滑动屏幕
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="2000"
        android:fromXDelta="100%p"
        android:toXDelta="0%p"/>
</set>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="2000"
        android:fromXDelta="0"
        android:toXDelta="-100%p"/>
</set>


(4)自定义的ViewFlipper:myViewFlipper

package com.example.navigationimgslide;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ViewFlipper;

/**
 * Created by zw 
 * 自定义的ViewFlipper
 */

public class MyViewFlipper extends ViewFlipper{

    public MyViewFlipper(Context context) {
        super(context);
    }

    public MyViewFlipper(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void showNext() {
        super.showNext();
        //从继承关系中发现当子view变化的时候会调用该方法,因此在这里弄个回�?
       mOnViewCountListener.viewCount(getDisplayedChild());
    }

    private OnViewCountListener mOnViewCountListener;

    public void setOnViewCountListener(OnViewCountListener mOnViewCountListener) {
        this.mOnViewCountListener = mOnViewCountListener;
    }

    public interface OnViewCountListener{
        void viewCount(int count);
    }
}


2.ViewPager实现左右滑动

(1)viewPagerActivity

package com.example.navigationimgslide;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

/**
 * @author zw
 * @deprecated viewpager的方式实现
 *
 */

public class ViewPagerActivity extends Activity {

  
	private ImageView imageView; 
	private ImageView[] imageViews;
	private ViewPager viewPager;
	private LinearLayout nvLayout;
	private List<ImageView> views;

	 private int[] str=new int[]{
	            R.drawable.image01,R.drawable.image02,
	            R.drawable.image03,R.drawable.image04};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pager);
        initView();

    }

	private void initView() {
		viewPager = (ViewPager) findViewById(R.id.viewPager);
		nvLayout = (LinearLayout) findViewById(R.id.viewPager_linear);
		initData();
	}

	
	@SuppressLint("NewApi")
	private void initData() {
		imageViews=new ImageView[str.length];
		views=new ArrayList<ImageView>();
		ImageView imgV=null;
		
		for (int i = 0; i < str.length; i++) {
			
		    imgV=new ImageView(this);
		    imgV.setScaleType(ScaleType.FIT_XY);
		    imgV.setImageResource(str[i]);
			views.add(imgV);
			
			ImageView dainImg=new ImageView(this);
			if (i==0) {
				dainImg.setImageResource(R.drawable.page);
			}else{
				dainImg.setImageResource(R.drawable.page_now);
			}
			
			LayoutParams layoutParams = new LayoutParams(
					new LinearLayout.LayoutParams(20,    
							20));
			layoutParams.setMargins(10, 0, 10, 0);
			nvLayout.addView(dainImg, layoutParams);
		}
		
		//设置Adapter  
        viewPager.setAdapter(new MyPagerAdapter());  
        //设置监听,主要是设置点点的背景  
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				setImageBackground(arg0 % (str.length));
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});  
       
	}
	
	/** 
     * 设置选中的的背景 
     * @param selectItems 
     */  
	private void setImageBackground(int i) {
		// TODO Auto-generated method stub
		ImageView imageView=null;
		for (int j = 0; j < str.length; j++) {
			imageView=(ImageView) nvLayout.getChildAt(j);
			if (i==j) {
				imageView.setImageResource(R.drawable.page);
			}else {
				imageView.setImageResource(R.drawable.page_now);
			}
		}
	}
	class MyPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return views.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			// TODO Auto-generated method stub
			((ViewPager) container).removeView(views.get(position));
		}

		/**
		 * 载入图片进去,用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(views.get(position));
			return views.get(position);
		}
	}
	
	
	
}

(2)activity_pager

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="240dp"
    >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="240dp"/>
    
    <LinearLayout
        android:id="@+id/viewPager_linear"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:background="#4ccc"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" />

</RelativeLayout>

参考文献:http://blog.csdn.net/zhangjinhuang/article/details/26287959

                    http://blog.csdn.net/chunqiuwei/article/details/50547290


源码下载:http://download.csdn.net/download/zhang106209/9998696

       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值