我有一个带有项目的列表视图,每次我点击一个列表项目时,我都需要知道我触摸到的是屏幕的左侧还是右侧。为了实现这一点,我编写了以下代码:
testListView.setOnItemClickListener(((parent, view, position, id) -> {
view.setOnTouchListener(new View.OnTouchListener() {
private long startClickTime = 0;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startClickTime = System.currentTimeMillis();
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
if (System.currentTimeMillis() - startClickTime < ViewConfiguration.getTapTimeout()) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
float leftPersentage = (dpWidth) * 100 / 100;
int x = (int) motionEvent.getX();
if (x < leftPersentage) {
Toast.makeText(context,"I have touched the left side of screen",Toast.LENGTH_SHORT);
} else {
Toast.makeText(context,"I have touched the right side of screen",Toast.LENGTH_SHORT);
}
}
}
return true;
}
});
}));这是可行的,但是为了让Toast出现,我需要按两次List元素,我认为这是因为我第一次单击list item元素时,它会注册OnTouchListener,然后,如果我再次单击,它就会触发。
我如何修复这种奇怪的行为,以便只需单击一次即可触发on touch侦听器?
发布于 2020-10-06 23:21:31
您需要在getView函数上的ListView适配器上设置setOnTouchListener,而不是在setOnItemClickListener上。
https://stackoverflow.com/questions/64228349
复制相似问题