【问题标题】:Android get position listview in OnTouchListener()Android 在 OnTouchListener() 中获取位置列表视图
【发布时间】:2014-06-16 19:43:44
【问题描述】:

我有一个列表视图,用户可以在其中“滑动”以从列表视图中删除项目。但我希望有机会看到这个项目的“细节”。当用户“点击”一个项目时,我想调用一个新活动。

我用它来允许滑动删除:

View.OnTouchListener mTouchListener = new View.OnTouchListener()

所以我将它与适配器一起使用:

    mAdapter = new TestAdapter(getActivity(),
            R.layout.layout_test, list, mTouchListener);
    listV.setAdapter(mAdapter);

在使用它之前,我使用 onItemClick 来获取所选项目的位置。

但是如果没有 onItemClick 函数我如何获得 POSITION 呢?

【问题讨论】:

标签: android listview android-listview adapter


【解决方案1】:

要知道 ArrayAdapter 中的位置,您可以使用 adapter.getPosition(view) http://developer.android.com/reference/android/widget/ArrayAdapter.html#getPosition(T).

您可以在适配器中使用带有 onListItemClick 的 TouchListener 来处理滑动操作和单击操作(例如打开详细信息)。

还可以使用 TouchListener,您可以使用类似于 Roman Nurik 代码的代码来通过单击的视图检索位置。

https://github.com/romannurik/Android-SwipeToDismiss/blob/master/src/com/example/android/swipedismiss/SwipeDismissListViewTouchListener.java

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

if (mDownView != null) {
    mDownX = motionEvent.getRawX();
    mDownY = motionEvent.getRawY();
    mDownPosition = mListView.getPositionForView(mDownView);
 }

【讨论】:

    【解决方案2】:

    1) 您应该为ListView 创建您的custom Adapter
    2) 在AdaptergetView 方法中,您应该为每个项目创建OnTouchListenerLayoutrootView)。

    【讨论】:

    • 嗯,我有一个自定义适配器,谢谢你的建议,我没有为每个项目创建一个 OnTouchListener,但我设置了 row.setId(position);在我的自定义适配器中,我在我唯一的函数 OnTouchListener 中使用 view.getId() 得到它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多