android开发: 我有一个LineaLayout要监听左滑和右滑给点示例代码
你可以使用GestureDetector来监听左滑和右滑事件。以下是一个示例代码:
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Toast;
public class SwipeLinearLayout extends LinearLayout {
private GestureDetectorCompat mGestureDetector;
public SwipeLinearLayout(Context context) {
super(context);
init(context);
}
public SwipeLinearLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SwipeLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mGestureDetector = new GestureDetectorCompat(context, new MyGestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
// 判断滑动的方向
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
// 右滑
Toast.makeText(getContext(), "右滑", Toast.LENGTH_SHORT).show();
} else {
// 左滑
Toast.makeText(getContext(), "左滑", Toast.LENGTH_SHORT).show();
}
return true;
}
}
return false;
}
}
}
你可以将以上代码保存成一个名为SwipeLinearLayout的类,并在布局文件中使用该自定义布局。当你在该布局上进行左滑或右滑动作时,会显示相应的Toast提示信息
原文地址: https://www.cveoy.top/t/topic/iJRD 著作权归作者所有。请勿转载和采集!