In my application I have a Touchlistener for my ListView. With the TouchListener I'm able to get the X and Y coordinates from the touch event. Now I want to get the clicked item from the ListView. How can I get the position of the click item in the listView only with an onTouchListener? I do not want to use a 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;
}
i am get it from SwipeListView Jake Wharton
the best way it to use this methods pointToPosition(int x, int y) and pointToRowId(int x, int y)
If it is not mandatory that you use a TouchListener
, I'd highly recommend using an OnItemClickListener
. It will simplify your life greatly.
Other than that, you'll have to get the current offset and scroll position of the ListView
, the height of each row and then do some math to determine whether the point (x,y) lies in the polygon of each row. Since the rows are rectangles that math isn't too difficult, but using OnItemClickListener
would be much, much easier.
Additionally, if you do need to use TouchListener
, you could also use OnItemClickListener
to set a value on your Adapter
class (or somewhere else) indicating the most recent item clicked. Then, in your TouchListener
you could check that value and use that to correlate the (x,y) coordinate and ListView
item. This, of course, depends on the OnItemClickListener
being run first. If the inverse is true, you could make it work but instead store the touch position in using the TouchListener
and then correlate it in the OnItemClickListener
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With