仅使用 OnTouchListener 从 ListView 获取项目 [英] Get Item from ListView only with OnTouchListener

查看:27
本文介绍了仅使用 OnTouchListener 从 ListView 获取项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我的 ListView 有一个 Touchlistener.使用 TouchListener,我可以从触摸事件中获取 X 和 Y 坐标.现在我想从 ListView 中获取点击的项目.如何仅使用 onTouchListener 获取 listView 中单击项的位置?我不想使用 onItemClickedListener.

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;
            }

我从 SwipeListView 得到它杰克·沃顿

这篇关于仅使用 OnTouchListener 从 ListView 获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆