手势监听之OnTouchListener与OnGestureListener

我们可以通过实现这两个接口中的相应方法来完成对用户在屏幕上的手势运动轨迹做监听,可以实现一个简单的左右或者上下滑动来切换屏幕。总共通过3步来完成。第一步:先实现OnTouchuListener和OnGestureListener这两个接口。第二步:实例化一个GestureDetector对象,并且获取当前页面的布局对该布局设置setOnTouchListener(this)和setLongClickable(true)注意必须要同时设置这两个方法否则无法实现手势运动监听。第三步:重写这两个接口中最主要的两个方法:boolean onTouch(View v, MotionEvent event),boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)。

代码:

public class MyAcitivity2 extends Activity implements OnTouchListener,OnGestureListener{ //第一步

//第二步

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);  
setContentView(R.layout.MyActivity);

gd = new GestureDetector((OnGestureListener)this); 
LinearLayout ll = (LinearLayout) findViewById(R.id.myactivitylayout);  
ll.setOnTouchListener(this);  
ll.setLongClickable(true);
}

//第三步:最主要的两个方法

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
if(e1.getX() - e2.getX() > FLING_MIN_DISTANCE&&Math.abs(velocityX) > FLING_MIN_VELOCITY)  {   //向左滑动
Intent intent = new Intent(this,MyActivity1.class);  
startActivity(intent);  
finish();
}  
else if (e2.getX()-e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) >FLING_MIN_VELOCITY) {  
//向右滑动
Intent intent = new Intent(this, Setup1Activity.class);  
startActivity(intent);  
finish();

return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gd.onTouchEvent(event);
}

}

这样就可以通过上下左右滑动来实现切换屏幕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值