DrawerLayout 中listView 滑动不好控制(竖直滑动和水平方向滑动判断)

在Android中,自定义MyDrawerLayout类继承DrawerLayout,通过覆写onInterceptTouchEvent和onTouchEvent方法,利用MotionEvent的ACTION_DOWN、ACTION_MOVE事件判断用户的滑动方向。当水平滑动距离大于垂直滑动距离的四倍时,拦截触摸事件,实现水平滑动;反之,允许竖直滑动。这样可以精确控制DrawerLayout中ListView的滑动行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;


public class MyDrawerLayout extends DrawerLayout {


public MyDrawerLayout(Context context) {
this(context, null);
}


public MyDrawerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}


public MyDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final ViewConfiguration configuration = ViewConfiguration
.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
}


private int mTouchSlop;
private float mLastMotionX;
private float mLastMotionY;


@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
final float x = ev.getX();
final float y = ev.getY();


switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionX = x;
mLastMotionY = y;
break;


case MotionEvent.ACTION_MOVE:
int xDiff = (int) Math.abs(x - mLastMotionX);
int yDiff = (int) Math.abs(y - mLastMotionY);
final int x_yDiff = xDiff * xDiff + yDiff * yDiff;


boolean xMoved = x_yDiff > mTouchSlop * mTouchSlop;


if (xMoved) {
if (xDiff > yDiff * 4) {
return true;
} else {
return false;
}
}
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException ex) {
}
return false;
}


@Override
public boolean onTouchEvent(MotionEvent ev) {
try {
return super.onTouchEvent(ev);
} catch (IllegalArgumentException ex) {
}
return false;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值