android – 仅使用OnTouchListener从ListView获取项目
作者:互联网
在我的应用程序中,我有一个Touchlistener用于我的ListView.使用TouchListener,我可以从触摸事件中获取X和Y坐标.现在我想从ListView获取被点击的项目.如何使用onTouchListener获取listView中单击项的位置?我不想使用onItemClickedListener.
解决方法:
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child; // This is your down view
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
view.onTouchEvent(motionEvent);
return true;
}
我从SwipeListView Jake Wharton开始
标签:android,ontouchlistener,android-listview 来源: https://codeday.me/bug/20191001/1837329.html