public class MainActivity extends AppCompatActivity {
public static final float FLIP_DISTANCE = 50;
GestureDetector mDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
@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) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
Intent intent = new Intent(MainActivity.this, RightActivity.class);
startActivity(intent);
Log.d("TAG", "向左滑");
return true;
}
if (e2.getX() - e1.getX() > FLIP_DISTANCE) {
Intent intent = new Intent(MainActivity.this, LeftActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.move_left_in,R.anim.move_right_out);
Log.d("TAG", "向右滑");
return true;
}
if (e1.getY() - e2.getY() > FLIP_DISTANCE) {
Log.d("TAG", "向上滑...");
return true;
}
if (e2.getY() - e1.getY() > FLIP_DISTANCE) {
Log.d("TAG", "向下滑...");
return true;
}
Log.d("TAG", e2.getX() + " " + e2.getY());
return false;
}
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mDetector.onTouchEvent(event);
}
}
overridePendingTransition:
这个函数有两个参数,一个参数是第一个activity进入时的动画,另外一个参数则是第二个activity退出时的动画。
这里需要特别说明的是,关于overridePendingTransition这个函数,有两点需要主意
1. 它必需紧挨着startActivity()或者finish()函数之后调用”
2. 它只在android2.0以及以上版本上适用
下面是/res/anim文件夹下的两个文件,注意,anim文件夹在新建Eclipse工程中默认是不存在的,因此如果第一次使用,需要自己新建这个目录
move_left_in.xml:
<!-- 左侧屏幕外:-100%p 屏幕内:0 右侧屏幕外:100%p-->
<!-- 从左侧屏幕外进入屏幕 -->
<translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="600"/>
move_right_out.xml:
<!-- 左侧屏幕外:-100%p 屏幕内:0 右侧屏幕外:100%p-->
<!-- 从右侧退出屏幕 -->
<translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="600"/>
这样就可以实现在MainActivity中,通过手指向右滑动的方式,进入OtherAcitivity了,同时在切换过程中,会有动画效果。