草庐IT

Android - ListView 像三星联系人一样向左/向右滑动 ListView

coder 2023-06-06 原文

我正在开发一个应用程序,我需要一个类似于我的三星 Galaxy S 的联系人 ListView 的 ListView:

当我向右滑动手指时,我可以向该联系人发送消息。

当我向右滑动手指时,我可以调用我的联系人。

我有我的 ListView,只需要它的功能......

提前致谢。

PD: 我搜索了很多,没有找到任何东西。最相似的: Resource for Android Slight Left/Right Slide action on listview

最佳答案

在另一篇文章中,有一个指向此 Google 代码的链接:https://gist.github.com/2980593 来自此 Google+ 帖子:https://plus.google.com/u/0/113735310430199015092/posts/Fgo1p5uWZLu . 这是一个滑动关闭功能。

您可以由此提供自己的“滑动到操作”代码。所以这是我的版本,如果我可以个性化左右 Action 并且你可以触发 Dismiss 动画(这只是 Roman Nuric 代码的修改)。

你必须在你的项目中包含这个类:

public class SwipeListViewTouchListener implements View.OnTouchListener {
    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private ListView mListView;
    private OnSwipeCallback mCallback;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
    private boolean dismissLeft = true;
    private boolean dismissRight = true;

    // Transient properties
    private List < PendingSwipeData > mPendingSwipes = new ArrayList < PendingSwipeData > ();
    private int mDismissAnimationRefCount = 0;
    private float mDownX;
    private boolean mSwiping;
    private VelocityTracker mVelocityTracker;
    private int mDownPosition;
    private View mDownView;
    private boolean mPaused;

    /**
     * The callback interface used by {@link SwipeListViewTouchListener} to inform its client
     * about a successful swipe of one or more list item positions.
     */
    public interface OnSwipeCallback {
        /**
         * Called when the user has swiped the list item to the left.
         *
         * @param listView               The originating {@link ListView}.
         * @param reverseSortedPositions An array of positions to dismiss, sorted in descending
         *                               order for convenience.
         */
        void onSwipeLeft(ListView listView, int[] reverseSortedPositions);

        void onSwipeRight(ListView listView, int[] reverseSortedPositions);
    }

    /**
     * Constructs a new swipe-to-action touch listener for the given list view.
     *
     * @param listView The list view whose items should be dismissable.
     * @param callback The callback to trigger when the user has indicated that she would like to
     *                 dismiss one or more list items.
     */
    public SwipeListViewTouchListener(ListView listView, OnSwipeCallback callback) {
        ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = listView.getContext().getResources().getInteger(
            android.R.integer.config_shortAnimTime);
        mListView = listView;
        mCallback = callback;
    }

    /**
     * Constructs a new swipe-to-action touch listener for the given list view.
     * 
     * @param listView The list view whose items should be dismissable.
     * @param callback The callback to trigger when the user has indicated that she would like to
     *                 dismiss one or more list items.
     * @param dismissLeft set if the dismiss animation is up when the user swipe to the left
     * @param dismissRight set if the dismiss animation is up when the user swipe to the right
     * @see #SwipeListViewTouchListener(ListView, OnSwipeCallback, boolean, boolean)
     */
    public SwipeListViewTouchListener(ListView listView, OnSwipeCallback callback, boolean dismissLeft, boolean dismissRight) {
        this(listView, callback);
        this.dismissLeft = dismissLeft;
        this.dismissRight = dismissRight;
    }

    /**
     * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
     *
     * @param enabled Whether or not to watch for gestures.
     */
    public void setEnabled(boolean enabled) {
        mPaused = !enabled;
    }

    /**
     * Returns an {@link android.widget.AbsListView.OnScrollListener} to be added to the
     * {@link ListView} using
     * {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}.
     * If a scroll listener is already assigned, the caller should still pass scroll changes
     * through to this listener. This will ensure that this
     * {@link SwipeListViewTouchListener} is paused during list view scrolling.</p>
     *
     * @see {@link SwipeListViewTouchListener}
     */
    public AbsListView.OnScrollListener makeScrollListener() {
        return new AbsListView.OnScrollListener() {@
            Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
            }

            @
            Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {}
        };
    }

    @
    Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mListView.getWidth();
        }

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

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

                    mVelocityTracker = VelocityTracker.obtain();
                    mVelocityTracker.addMovement(motionEvent);
                }
                view.onTouchEvent(motionEvent);
                return true;
            }

        case MotionEvent.ACTION_UP:
            {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getRawX() - mDownX;
                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(500); // 1000 by defaut but it was too much
                float velocityX = Math.abs(mVelocityTracker.getXVelocity());
                float velocityY = Math.abs(mVelocityTracker.getYVelocity());
                boolean swipe = false;
                boolean swipeRight = false;

                if (Math.abs(deltaX) > mViewWidth / 2) {
                    swipe = true;
                    swipeRight = deltaX > 0;
                } else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) {
                    swipe = true;
                    swipeRight = mVelocityTracker.getXVelocity() > 0;
                }
                if (swipe) {
                    // sufficent swipe value
                    final View downView = mDownView; // mDownView gets null'd before animation ends
                    final int downPosition = mDownPosition;
                    final boolean toTheRight = swipeRight;
                    ++mDismissAnimationRefCount;
                    mDownView.animate()
                        .translationX(swipeRight ? mViewWidth : -mViewWidth)
                        .alpha(0)
                        .setDuration(mAnimationTime)
                        .setListener(new AnimatorListenerAdapter() {@
                        Override
                        public void onAnimationEnd(Animator animation) {
                            performSwipeAction(downView, downPosition, toTheRight, toTheRight ? dismissRight : dismissLeft);
                        }
                    });
                } else {
                    // cancel
                    mDownView.animate()
                        .translationX(0)
                        .alpha(1)
                        .setDuration(mAnimationTime)
                        .setListener(null);
                }
                mVelocityTracker = null;
                mDownX = 0;
                mDownView = null;
                mDownPosition = ListView.INVALID_POSITION;
                mSwiping = false;
                break;
            }

        case MotionEvent.ACTION_MOVE:
            {
                if (mVelocityTracker == null || mPaused) {
                    break;
                }

                mVelocityTracker.addMovement(motionEvent);
                float deltaX = motionEvent.getRawX() - mDownX;
                if (Math.abs(deltaX) > mSlop) {
                    mSwiping = true;
                    mListView.requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch (un-highlighting the item)
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                        (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mListView.onTouchEvent(cancelEvent);
                }

                if (mSwiping) {
                    mDownView.setTranslationX(deltaX);
                    mDownView.setAlpha(Math.max(0f, Math.min(1f,
                        1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }

    class PendingSwipeData implements Comparable < PendingSwipeData > {
        public int position;
        public View view;

        public PendingSwipeData(int position, View view) {
            this.position = position;
            this.view = view;
        }

        @
        Override
        public int compareTo(PendingSwipeData other) {
            // Sort by descending position
            return other.position - position;
        }
    }

    private void performSwipeAction(final View swipeView, final int swipePosition, boolean toTheRight, boolean dismiss) {
        // Animate the dismissed list item to zero-height and fire the dismiss callback when
        // all dismissed list item animations have completed. This triggers layout on each animation
        // frame; in the future we may want to do something smarter and more performant.

        final ViewGroup.LayoutParams lp = swipeView.getLayoutParams();
        final int originalHeight = swipeView.getHeight();
        final boolean swipeRight = toTheRight;

        ValueAnimator animator;
        if (dismiss)
            animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
        else
            animator = ValueAnimator.ofInt(originalHeight, originalHeight - 1).setDuration(mAnimationTime);


        animator.addListener(new AnimatorListenerAdapter() {@
            Override
            public void onAnimationEnd(Animator animation) {
                --mDismissAnimationRefCount;
                if (mDismissAnimationRefCount == 0) {
                    // No active animations, process all pending dismisses.
                    // Sort by descending position
                    Collections.sort(mPendingSwipes);

                    int[] swipePositions = new int[mPendingSwipes.size()];
                    for (int i = mPendingSwipes.size() - 1; i >= 0; i--) {
                        swipePositions[i] = mPendingSwipes.get(i).position;
                    }
                    if (swipeRight)
                        mCallback.onSwipeRight(mListView, swipePositions);
                    else
                        mCallback.onSwipeLeft(mListView, swipePositions);

                    ViewGroup.LayoutParams lp;
                    for (PendingSwipeData pendingDismiss: mPendingSwipes) {
                        // Reset view presentation
                        pendingDismiss.view.setAlpha(1f);
                        pendingDismiss.view.setTranslationX(0);
                        lp = pendingDismiss.view.getLayoutParams();
                        lp.height = originalHeight;
                        pendingDismiss.view.setLayoutParams(lp);
                    }

                    mPendingSwipes.clear();
                }
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {@
            Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                swipeView.setLayoutParams(lp);
            }
        });

        mPendingSwipes.add(new PendingSwipeData(swipePosition, swipeView));
        animator.start();
    }
}

从那里,您可以使用 ListView 将以下代码添加到 Activity 中的 onCreate 中:

// Create a ListView-specific touch listener. ListViews are given special treatment because
// by default they handle touches for their list items... i.e. they're in charge of drawing
// the pressed state (the list selector), handling list item clicks, etc.
SwipeListViewTouchListener touchListener =
    new SwipeListViewTouchListener(
        listView,
        new SwipeListViewTouchListener.OnSwipeCallback() {
            @Override
            public void onSwipeLeft(ListView listView, int [] reverseSortedPositions) {
                //  Log.i(this.getClass().getName(), "swipe left : pos="+reverseSortedPositions[0]);
                // TODO : YOUR CODE HERE FOR LEFT ACTION
            }

            @Override
            public void onSwipeRight(ListView listView, int [] reverseSortedPositions) {
                //  Log.i(ProfileMenuActivity.class.getClass().getName(), "swipe right : pos="+reverseSortedPositions[0]);
                // TODO : YOUR CODE HERE FOR RIGHT ACTION
            }
        },
        true, // example : left action = dismiss
        false); // example : right action without dismiss animation
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());

编辑: 要在滑动时添加颜色修改,您的代码必须位于 mDownView.setAlpha 附近的 case MotionEvent.ACTION_MOVE 中。

关于Android - ListView 像三星联系人一样向左/向右滑动 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9321016/

有关Android - ListView 像三星联系人一样向左/向右滑动 ListView的更多相关文章

  1. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  2. ruby - 可以像在 C# 中使用#region 一样在 Ruby 中使用 begin/end 吗? - 2

    我最近从C#转向了Ruby,我发现自己无法制作可折叠的标记代码区域。我只是想到做这种事情应该没问题:classExamplebegin#agroupofmethodsdefmethod1..enddefmethod2..endenddefmethod3..endend...但是这样做真的可以吗?method1和method2最终与method3是同一种东西吗?还是有一些我还没有见过的用于执行此操作的Ruby惯用语? 最佳答案 正如其他人所说,这不会改变方法定义。但是,如果要标记方法组,为什么不使用Ruby语义来标记它们呢?您可以使用

  3. java - Java 中的 "caller"和 Ruby 中的 "receiver"一样吗? - 2

    如果我说x.hello()在Java中,对象x正在“调用”它包含的方法。在Ruby中,对象x正在“接收”它包含的方法。这只是表达相同想法的不同术语,还是意识形态上的根本差异?来自Java,我发现Ruby的“接收器”想法非常令人困惑。也许有人可以解释这与Java的关系? 最佳答案 在您的示例中,x不调用hello()。包含该片段的任何对象都是“调用”(即,它是“调用者”)。在Java中,x可以称为接收者;它正在接收对hello()方法的调用。 关于java-Java中的"caller"和R

  4. ruby-on-rails - 如何在 ruby​​ on rails 中为 gmail 联系人创建访问 token - 2

    我正在使用Omniauth请求用户gmail凭据,因此我可以稍后请求用户friend/联系人。现在,我正在使用身份验证请求为我生成的访问token,在OmniauthCallbacksController中获取好友列表。像这样classUsers::OmniauthCallbacksController如何使用存储在数据库中的凭据创建新的访问token,以便从不同的Controller调用googleAPI? 最佳答案 从here获取您的client_id和client_secret|.这是一个粗略的脚本,可以很好地工作。根据您的需

  5. Ruby AWS::S3::S3Object (aws-sdk):是否有与 aws-s3 一样的流式数据方法? - 2

    在aws-s3中,有一种方法(AWS::S3::S3Object.stream)可让您将S3上的文件流式传输到本地文件。我无法在aws-sdk中找到类似的方法。即在aws-s3中,我这样做:File.open(to_file,"wb")do|file|AWS::S3::S3Object.stream(key,region)do|chunk|file.writechunkendendAWS::S3:S3Object.read方法确实将block作为参数,但似乎没有对其执行任何操作。 最佳答案 aws-sdkgem现在支持S3中对象的分

  6. 光度学中的能量、通量、出度、照度、强度、亮度参数及其联系 - 2

    光度学中的能量、通量、出度、照度、强度、亮度参数及其联系光度学中评价光的强弱有两种方式,一种是将光作为电磁波,考察其辐射的能量;另一种是以人眼视觉体验来评价光的强弱。前者被称为辐射量,后者被称为光学量。辐射量包括辐射能、辐通量、辐出量、辐照度、辐强度、辐亮度参数,与之相对应,光学量包括光能量、光通量、光出量、光照度、光强度、光亮度参数。通过该文章的阅读,读者还能掌握光学中的几个单位:流明,勒克斯,坎德拉,尼特的意义以及他们之间的关系。辐射量1.辐射能光以电磁波形式发射、传输或接收的能量。单位:焦耳。2.辐通量单位时间发射、传输和接收的辐射能。单位:瓦特。3.辐出度单位面积的辐射源辐射出的辐通量

  7. ruby - 在控制台中向左移动一个字符 - 2

    在控制台中,您可以像这样打印"\b"来删除光标左侧的字符(退格键)print"thelastcharisgoingtobeerased\b"#thelastcharisgoingtobeerased如何只向左移动一个位置而不是删除(向左箭头)? 最佳答案 这取决于终端类型和连接,但通常可以假定ANSI光标移动,因此光标向左是ESC+'['+'D':print"Thecursorshouldbebetweenthearrows:->参见http://ascii-table.com/ansi-escape-sequences.php获取

  8. c# - Ruby 是否像 C# 一样具有 Skip(n)? - 2

    在C#中你可以这样做:varlist=newList(){1,2,3,4,5};list.skip(2).take(2);//returns(3,4)我正在尝试学习所有Ruby可枚举方法,但我没有看到skip(n)的等效方法a=[1,2,3,4,5]a.skip(2).take(2)#takeexists,skipdoesn't那么,“最好的”Ruby方法是什么?所有这些都有效,但它们非常丑陋。a.last(a.length-2).take(2)(a-a.first(2)).take(2)a[2...a.length].take(2) 最佳答案

  9. ruby-on-rails - 我如何解析一个 Excel 文件,它会给我提供与视觉上完全一样的数据? - 2

    我正在使用Rails5(Ruby2.4)。我想阅读.xls文档,我想将数据转换为CSV格式,就像它出现在Excel文件中一样。有人推荐我使用Roo,所以我有book=Roo::Spreadsheet.open(file_location)sheet=book.sheet(0)text=sheet.to_csvarr_of_arrs=CSV.parse(text)但是,返回的内容与我在电子表格中看到的内容不同。例如,电子表格中的一个单元格有16:45.81当我从上面获取CSV数据时,返回的是"0.011641319444444444"如何解析Excel文档并准确获取我所看到的内容?我不在

  10. ruby - 像 Smalltalk 一样浏览 Ruby 代码? - 2

    与Smalltalk类层次结构浏览器最接近的等效项是什么?我见过一些解决方法,例如this,但它似乎不可编写脚本。 最佳答案 确实没有,至少没有包含静态和动态行为的类似Smalltalk的UI。Eclipse和IntelliJ都具有一定的结构洞察力。Eclipse有一种类似于浏览器的View。两者最大的问题是,除非您正在处理实时对象(例如,调试),否则您不一定知道对象的所有行为,因为有些行为是在运行时定义的。没有图像或部分运行时的静态View无法提供完整的图片。IntelliJ在解决问题方面做得不错。例如,具有attr_access

随机推荐