步骤1 :
继承ontouchlinstener和ongesturelisnter
重写ontouch方法,并重写ondown,onfling等方法,
在ontouch中调用ongesture的ontouch event ,将触摸事件传递给gesturelistener类处理
注意:
当前view要设置setLongClickable(true);
package com.touchtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity implements OnTouchListener,OnGestureListener{
public GestureDetector gesture;
private final int mindistance = 5;//滑动最小距离
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gesture =new GestureDetector(this, this);; //new gesturedector(Context context , OnGestureListener ongesturelistener )
LinearLayout linearlayout1 = (LinearLayout)findViewById(R.id.LinearLayout1);
linearlayout1.setOnTouchListener(this);
linearlayout1.setLongClickable(true); //***********注意
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return gesture.onTouchEvent(arg1); //************注意
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "屏幕按下", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
if((arg1.getX()-arg0.getX()>mindistance))
{Toast.makeText(this, "向右滑动", Toast.LENGTH_SHORT).show();}
else if((arg0.getX()-arg1.getX()>mindistance))
{Toast.makeText(this, "向左滑动", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}