【发布时间】:2021-01-21 11:36:28
【问题描述】:
我有一个包含项目的列表视图,每次单击 List Item 时,我都需要知道我是否触摸了屏幕的左侧或右侧。为了实现这一点,我编写了以下代码:
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 元素,我认为这是因为我第一次单击列表项元素时,它会注册 OnTouchListener,然后,如果我再次点击它就会启动。
如何解决这种奇怪的行为,以便一键触发 on touch 监听器?
【问题讨论】:
标签: android android-listview touch-event ontouchlistener onitemclicklistener