Android实现滑动选择图片

1、效果图


select.gif

2、开始实现,首先自定义一个RecyclerView,然后重写dispatchTouchEvent()方法,在里面添加一个监听器,监听滑动事件。代码如下:

package com.quanten.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * 文 件 名:  PhotoRecyclerView
 * 版    权:  Quanten Team. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  LLF
 * 修改时间:  2018/9/6 0006
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */


public class PhotoRecyclerView extends RecyclerView {
    private OnDispatchTouchListener mOnDispatchTouchListener;
    public PhotoRecyclerView(Context context) {
        this(context,null);
    }

    public PhotoRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PhotoRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean dispatchTouchEvent(final MotionEvent event) {
        if(mOnDispatchTouchListener != null)
        {
            mOnDispatchTouchListener.onDispatchTouch(event);
        }
        return super.dispatchTouchEvent(event);
    }

    public void setmOnDispatchTouchListener(OnDispatchTouchListener mOnDispatchTouchListener) {
        this.mOnDispatchTouchListener = mOnDispatchTouchListener;
    }

    public interface OnDispatchTouchListener{
        void onDispatchTouch(MotionEvent event);
    }
}

3、在图片选择页面监听用户选择图片事件,然后更新图片选择状态即可,主要代码如下:

 recyclerView.setmOnDispatchTouchListener(new PhotoRecyclerView.OnDispatchTouchListener()
        {
            @Override
            public void onDispatchTouch(MotionEvent event)
            {

                switch (event.getAction())
                {

                    case MotionEvent.ACTION_DOWN:
                        // 获取按下时的位置,x,y
                        selectPics.clear();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        View v = recyclerView.findChildViewUnder(event.getX(), event.getY());
                        if (v != null && !selectPics.contains(v.getTag()))
                        {
                            Log.d("PhotoSelectActivity", " getId=" + v.getTag());
                            Integer index=(Integer) v.getTag();
                            selectPics.add(index);
                            mAdapter.selectedPic(null, imageFolderBeanList.get(index), index);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        selectPics.clear();
                        break;

                }
            }
        });

4、代码已上传百度云,如有问题,欢迎评论!源码链接:https://pan.baidu.com/s/1MOdtjOZfkBoiGC_-twk1Cw

你可能感兴趣的:(Android实现滑动选择图片)