因为项目原因,要在多个页面实现左右滑动效果,要是在每个页面都写一遍太麻烦,所以把监听动作抽出来方便调用,代码如下:
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
public class MainActivity extends Activity implements OnTouchListener {
private RelativeLayout mLayout;
private GestureDetector mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetector(this, new MyGestureListener(this));
mLayout = (RelativeLayout) findViewById(R.id.layout1);
mLayout.setOnTouchListener(this);
mLayout.setLongClickable(true);
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return mGestureDetector.onTouchEvent(arg1);
}
}
MyGestureListener
import android.content.Context;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.Toast;
public class MyGestureListener implements OnGestureListener {
private Context context;
public MyGestureListener(Context context) {
super();
this.context = context;
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float x,
float y) {
// TODO Auto-generated method stub
if(e1.getX() - e2.getX() > 50 && Math.abs(x) > 0 ){
Toast.makeText(context, "left", 300).show();
} else if ( e2.getX() - e1.getX() > 50 && Math.abs(x) > 0 ){
Toast.makeText(context, "right", 300).show();
}
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>