之前学习到ViewFlipper实现一个Activity多个控件之间的滑动切换,现在来学习多个activity之间的滑动切换。
1.继承OnTouchListner和OnGestureListener.
public class WeatherActivity extends Activity implements OnTouchListener,OnGestureListener{
// 2.创建GesTureDetector对象(创建时必须实现OnGestureListnener监听器实
//例) GestureDetector gd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gd = new GestureDetector((OnGestureListener)this);
// 3.为当前Acitivity的布局页面添加setOnTouchListener事件。(OnCreate函数)
LinearLayout ll = (LinearLayout) findViewById(R.id.weather_layout);
ll.setOnTouchListener(this);
ll.setLongClickable(true);
//注意:若不加setLongClickable(true)的话OnFling会失效,如果不写这句的话OnGestureListener的重写方法OnDown方法返回true也可以。只有这样,view才///能够处理不同于Tap(轻触)的hold(即ACTION_MOVE,或者多个ACTION_DOWN),我们同样可以通过layout定义中的android:longClickable来做到这一点。 //4.将Acityvity的TouchEvent事件交给GestureDetector处理@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return gd.onTouchEvent(event);
}
// 5.重载onFling函数
@Override
//e1 The first down motion event that started the fling.手势起点的移动事件
//e2 The move motion event that triggered the current onFling.当前手势点的移动事件
//velocityX The velocity of this fling measured in pixels per second along the x axis.每秒x轴方向移动的像素
//velocityY The velocity of this fling measured in pixels per second along the y axis.每秒y轴方向移动的像素
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
if(e1.getX() - e2.getX() > FLING_MIN_DISTANCE&&Math.abs(velocityX) > FLING_MIN_VELOCITY)
{
Intent intent = new Intent(WeatherActivity.this,CityActivity.class);
startActivity(intent);
Toast.makeText(this, "向左手势", Toast.LENGTH_SHORT).show();
}
else if (e2.getX()-e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) >FLING_MIN_VELOCITY) {
//切换Activity
Intent intent = new Intent(WeatherActivity.this, IndexActivity.class);
startActivity(intent);
Toast.makeText(this, "向右手势", Toast.LENGTH_SHORT).show();
}
return false;
}