Get Item from ListView only with OnTouchListener

Cilenco picture Cilenco · Jun 29, 2013 · Viewed 15.1k times · Source

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.

Answer

Ozik  Abdullaev picture Ozik Abdullaev · Jun 29, 2013
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