效果
1.activity加implements
implements GestureDetector.OnGestureListener
2.
<ViewFlipper
android:id="@+id/mars_bg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3.
private GestureDetector gestureDetector = null;
private ViewFlipper marsBg;
private int[] imageID = {R.drawable.bg_ast1, R.drawable.bg_main, R.drawable.bg_home};
4.oncreat中
// 生成GestureDetector对象,用于检测手势事件
gestureDetector = new GestureDetector(this);
// 添加用于切换的图片
for (int value : imageID) {
// 定义一个ImageView对象
ImageView image = new ImageView(this);
image.setImageResource(value);
// 充满父控件
image.setScaleType(ImageView.ScaleType.FIT_XY);
// 添加到viewFlipper中
marsBg.addView(image, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
5.重写继承的方法
@Override
public boolean onTouchEvent(MotionEvent event) {
return this.gestureDetector.onTouchEvent(event);
}
@Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
//对手指滑动的距离进行了计算,如果滑动距离大于120像素,就做切换动作,否则不做任何切换动作。
// 从左向右滑动
if (arg0.getX() - arg1.getX() > 120) {
// 添加动画
this.marsBg.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_left_in));
this.marsBg.setOutAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_left_out));
this.marsBg.showNext();
return true;
}// 从右向左滑动
else if (arg0.getX() - arg1.getX() < -120) {
this.marsBg.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_right_in));
this.marsBg.setOutAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_right_out));
this.marsBg.showPrevious();
return true;
}
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
6.anim
push_left_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="500" />
<alpha android:fromAlpha="0.1" android:toAlpha="1.0"
android:duration="500" />
</set>
push_left_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="500" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.1"
android:duration="500" />
</set>
push_right_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="500" />
<alpha android:fromAlpha="0.1" android:toAlpha="1.0"
android:duration="500" />
</set>
push_right_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="500" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.1"
android:duration="500" />
</set>