Android ListView,滑动操作

15

我有一个带有一些文本的列表视图。我想在滑动操作时显示图像(几乎就像 Gmail 应用程序一样)。例如,如果我从左向右滑动 - 我的列表项向右移动,图片从左侧滑动。我的列表项最多只能向右移动到图像宽度。滑动停止后,列表项将移动到起始位置。我怎么做这种事情呢? example


你解决过这个问题吗?我也想做类似的事情。 - egfconnor
不,我还没有找到任何有良好文档记录的例子。 - BoredT
我最终创建了自己的解决方案。我很快会开源它,并在之后回复您。它有点不同,但应该非常适应您的使用。我甚至可以将其整合到您的用例中。 - egfconnor
1
你可以尝试使用这个库:https://github.com/47deg/android-swipelistview。 - Jigar Shekh
这个库在滑动行时显示了一个布局。您可以在该布局中指定您的图像。虽然它的主要目的是删除,但您也可以用它来做其他用途。它还支持指定滑动方向。https://github.com/chinmoy12/Delete-ListView-Row-Like-iOS - ihsan
显示剩余3条评论
3个回答

2

请查看这里,了解ListView滑动相关的技术内容。

在那里,您可以看到列表视图向右滑动以显示视图。

快照:

enter image description here

main_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:swipe="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

   <com.fortysevendeg.swipelistview.SwipeListView
            android:id="@+id/example_swipe_lv_list"
            android:listSelector="#00000000"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            swipe:swipeFrontView="@+id/front"
            swipe:swipeBackView="@+id/back"
            swipe:swipeDrawableChecked="@drawable/choice_selected"
            swipe:swipeDrawableUnchecked="@drawable/choice_unselected"
            swipe:swipeCloseAllItemsWhenMoveList="true"
            swipe:swipeMode="both"
            />

</LinearLayout>

1

我找不到一个只做这个的库,但是自己制作也不难。正如Nick所指出的那样,请查看android-swipetodismiss,查看SwipeDismissListViewTouchListener.java

首先,您需要为ListView的子项创建一个自定义View。您需要一个ImageView,它被另一个包含文本的View覆盖。

然后,您可以将onTouch()监听器添加到您的ListView上。在MotionEvent.ACTION_DOWN(当您开始手势时)时,您需要获取触摸坐标并计算您正在触摸的ListView中的哪个子项,例如:

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

MotionEvent.ACTION_MOVE 事件中,您需要测量触摸点与 MotionEvent.ACTION_DOWN 事件中接触的点之间的 X 坐标差:

float deltaX = motionEvent.getRawX() - mDownX;

因此,您需要翻译包含文本的View,以便显示ImageView

mDownView.setTranslationX(deltaX);

当你抬起手指时,只需设置 mDownView .setTranslationX(0),图像就会再次被覆盖。这只是一个指南,还有一些细节没有涵盖,但你应该能够从这里开始。

1

您可以使用GestureDetector的onFling()事件。它将提供MotionEvent点和触摸速度点,使用这些点您可以识别手势并使用动画从左到右或从右到左加载视图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接