Android中实现滑动翻页—使用ViewFlipper

理论:http://blog.csdn.net/arui319/article/details/7210163
代码如下:
public class ViewFlipperActivity extends Activity implements OnGestureListener { 
   
    private static final int FLING_MIN_DISTANCE = 100; 
    private ViewFlipper flipper; 
    private GestureDetector detector; 
    private int[] resuorce = new int[]{R.drawable.jt1,R.drawable.jt2,R.drawable.jt3,R.drawable.jt4,
        R.drawable.jt5,R.drawable.jt6,R.drawable.jt7};
   
    protected void onCreate(Bundle savedInstanceState)
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.view_sns_activity); 
        /*
         *  注册一个GestureDetector 
         */
        detector = new GestureDetector(this);
       
        flipper = (ViewFlipper) findViewById(R.id.viewFlipper1); 
        for (int i = 0; i < resuorce.length; i++)
        {
            ImageView image = new ImageView(this);
            image.setBackgroundResource(resuorce[i]);
            flipper.addView(image);
        }
       
    } 
 
    public boolean onTouchEvent(MotionEvent event)
    { 
        /*
         *  将触屏事件交给手势识别类处理 
         */
        return this.detector.onTouchEvent(event); 
    } 
 
    public boolean onDown(MotionEvent e) { 
        return false; 
    } 
 
    public void onShowPress(MotionEvent e) { 
    } 
 
    public boolean onSingleTapUp(MotionEvent e) { 
        return false; 
    } 
 
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,  float distanceY) { 
        return false; 
    } 
 
    public void onLongPress(MotionEvent e) { 
    } 
 
    /*
     *
     */
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    { 
        boolean is_fling = false;
        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE)
        { 
            /*
             * 设置View进入和退出的动画效果 
             */
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,  android.R.anim.fade_in)); 
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,  android.R.anim.fade_out)); 
            this.flipper.showNext(); 
            is_fling = true; 
        } 
        if (e1.getX() - e2.getX() < -FLING_MIN_DISTANCE)
        { 
            this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,  android.R.anim.fade_in)); 
            this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,  android.R.anim.fade_out)); 
            this.flipper.showPrevious(); 
            is_fling = true; 
        } 
        return is_fling; 
    }

xml:

android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center"
android:id="@+id/viewSnsLayout">

android:layout_width="wrap_content" android:id="@+id/viewFlipper1">


你可能感兴趣的:(Android)