Android 实现可拖拽列表和多选功能

这段时间在做一个app,整体功能不是非常复杂,所以感觉一直在啃老本,直到碰到一个需求,要实现列表拖拽功能,经过一番绞尽脑汁的探索加上参考各路大神的博客终于做完了,在此和大家分享自己的经历

我最开始想到的方案是用第三方库,所以借助万能的百度查到了一个DragsortListview,然后就添加进项目中开始写Demo,结果发现各种坑爹(这都啥玩意儿,还有这么多人给星),然后我冷静地想了一下开始学Android的时候正是RecyclerView大火各方大神写动效,什么瀑布流,网格好像就有这个拖动效果,百度一查,谷歌爸爸早就把拖动的接口预留在RecyclerView里面了(掀桌子)

RecyclerView是ViewGroup的子类,没有像ListView那样OnItemClickListener接口,点击事件需要自己实现和传值
ItemTouchHelper是ItemDecoration的子类,用于定制RecyclerView的动效,ItemDecoration用于设置列表条目的分割线,ItemTouchHelper.Callback是联系RecyclerView.Adapter和ItemTouchHelper的关键,在其中可以设置侧滑和拖动等多种手势

注意ReportListActivity中有两个监听接口,一个是View.OnClickListener,另外一个是RecyclerAdapter.Callback,为了区分开来,前者我用接口实现,后者用内部类实现

我已经把这个模块放到GitHub上开源了,有兴趣可以看一下
https://github.com/caoguoly940713/UIFrame

废话不多说,直接上主菜
主窗口代码:

/**
 * 编辑状态下长按拖动条目
 * 1.通过ItemTouchHelper.Callback实现长按拖动
 * 2.通过isEditable的值判断是否编辑状态,初值是false
 * 3.切换编辑状态要把isEditable的值取反,并改变复选框图标状态
 * 4.在编辑状态下,按返回键回到非编辑状态
 * 5.RecyclerView的点击事件通过RecyclerAdapter.Callback实现
 */

public class ReportListActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "ReportListActivity";

    @BindView(R.id.tv_title_middle)
    TextView title;
    @BindView(R.id.title_left)
    ImageView backButton;
    @BindView(R.id.online_report_listview)
    RecyclerView mRecyclerView;
    @BindView(R.id.edit_tv)
    TextView edit;
    @BindView(R.id.filter_tv)
    TextView filter;
    @BindView(R.id.btn_delete)
    TextView delete;
    @BindView(R.id.btn_release)
    TextView release;
    @BindView(R.id.btn_close)
    TextView close;
    @BindView(R.id.btn_top)
    TextView top;

    private Context mContext;
    private boolean isEditable;
    private RecyclerAdapter mAdapter;
    private List mClsOnlineReportList;
    private ItemTouchHelper itemTouchHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_report);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initData() {
        mContext = this;
        getOfflineData(20);

        setIsEditable(false);
        OnlineReportListCallback callback = new OnlineReportListCallback(mAdapter);
        itemTouchHelper = new ItemTouchHelper(callback);

        setRecyclerViewDraggable(false);
    }

    private void getOfflineData(int num) {

        List clsOnlineReportList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            ClsOnlineReport onlineReport = new ClsOnlineReport();
            onlineReport.setActiveDate("activeDate " + i);
            onlineReport.setAutoCloseDate("autoCloseDate " + i);
            onlineReport.setBulletinID("bulletinID " + i);
            onlineReport.setBulletinTime("bulletinTime " + i);
            onlineReport.setBulletinTitle("bulletinTitle " + i);
            onlineReport.setCreater("creater " + i);
            onlineReport.setCreaterID("creater " + i);
            onlineReport.setIsActive("isActive " + i);
            onlineReport.setModiManID("modiManID " + i);
            onlineReport.setModiManName("modiManName " + i);
            onlineReport.setOnTop("onTop " + i);
            onlineReport.setOrderNum("oderNum " + i);
            clsOnlineReportList.add(onlineReport);
        }

        mClsOnlineReportList = clsOnlineReportList;
        mAdapter = new RecyclerAdapter(mClsOnlineReportList);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initView() {
        title.setText("可拖拽列表");
        edit.setVisibility(View.VISIBLE);
        hideBottomMenu();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
    }

    private void initListener() {
        filter.setOnClickListener(this);
        backButton.setOnClickListener(this);
        edit.setOnClickListener(this);
        delete.setOnClickListener(this);
        release.setOnClickListener(this);
        close.setOnClickListener(this);
        top.setOnClickListener(this);

        mAdapter.setmCallback((v, position) -> {
            switch (v.getId()) {
                case R.id.view_parent_1:
                case R.id.view_parent_2:
                    ClsOnlineReport clsOnlineReport = mClsOnlineReportList.get(position);
                    if (getIsEditable()) {
                        if (clsOnlineReport.getIsCheckBoxVisible()) {
                            clsOnlineReport.setIsChecked(!clsOnlineReport.getIsChecked());
                            mAdapter.notifyDataSetChanged();
                        }

                        for (int i = 0; i < mClsOnlineReportList.size(); i++) {
                            ClsOnlineReport onlineReport = mClsOnlineReportList.get(i);
                            if (onlineReport.getIsChecked()) {
                                showBottomMenu();
                                break;
                            }
                            if (i == mClsOnlineReportList.size() - 1) {
                                hideBottomMenu();
                            }
                        }
                    } else {
                        Intent intent = new Intent(mContext, ReportDetailActivity.class);
                        intent.putExtra("bulletinID", clsOnlineReport.getBulletinID());
                        startActivityForResult(intent, 16371);
                    }
            }
        });
    }

    @Override
    public void onBackPressed() {

        if (getIsEditable()) {
            switchEditable();
        } else {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.title_left) {
            if (getIsEditable()) {
                switchEditable();
            } else {
                finish();
            }
        }
        if (v.getId() == R.id.edit_tv) {
            switchEditable();
        }

        switch (v.getId()) {

            case R.id.btn_top:
            case R.id.btn_close:
            case R.id.btn_release:
            case R.id.btn_delete:
                Toast.makeText(mContext, "在此处调用接口", Toast.LENGTH_SHORT).show();
        }

    }


    private void hideBottomMenu() {
        delete.setVisibility(View.GONE);
        top.setVisibility(View.GONE);
        release.setVisibility(View.GONE);
        close.setVisibility(View.GONE);
    }

    private void showBottomMenu() {
        delete.setVisibility(View.VISIBLE);
        top.setVisibility(View.VISIBLE);
        release.setVisibility(View.VISIBLE);
        close.setVisibility(View.VISIBLE);
    }

    private void switchEditable() {

        setIsEditable(!getIsEditable());

        for (ClsOnlineReport clsOnlineReport : mClsOnlineReportList) {
            clsOnlineReport.setIsCheckBoxVisible(getIsEditable());
            clsOnlineReport.setIsChecked(false);
        }

        mAdapter.notifyDataSetChanged();
        hideBottomMenu();

        setRecyclerViewDraggable(getIsEditable());
    }

    public boolean getIsEditable() {
        return isEditable;
    }

    public void setIsEditable(boolean isEditable) {
        this.isEditable = isEditable;
    }

    private void setRecyclerViewDraggable(boolean draggable) {
        if (draggable) {
            itemTouchHelper.attachToRecyclerView(mRecyclerView);
        } else {
            itemTouchHelper.attachToRecyclerView(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == 16371 && resultCode == RESULT_OK) {
            refreshData();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void refreshData() {
        Toast.makeText(mContext, "在此处调用接口", Toast.LENGTH_SHORT).show();
    }
}

布局文件代码:





    

    

    

        

        

        

        
    

适配器代码:

/**
 * 可拖拽列表的适配器,
 * 1.需要实现OnlineReportListCallback.ItemTouchMoveListener
 * 2.持有一个接口用于传递position
 */
public class RecyclerAdapter extends RecyclerView.Adapter implements OnlineReportListCallback.ItemTouchMoveListener, View.OnClickListener {

    private List mList;
    private Callback mCallback;

    public RecyclerAdapter(List mList) {
        this.mList = mList;
    }

    public void setmCallback(Callback mCallback) {
        this.mCallback = mCallback;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.item_report_list, parent, false);
        return new ItemHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        ClsOnlineReport clsOnlineReport = mList.get(position);
        ItemHolder itemHolder = (ItemHolder) holder;

        if (clsOnlineReport.getIsCheckBoxVisible()) {
            itemHolder.checkbox.setVisibility(View.VISIBLE);
            itemHolder.drag.setVisibility(View.VISIBLE);
        } else {
            itemHolder.checkbox.setVisibility(View.GONE);
            itemHolder.drag.setVisibility(View.GONE);
        }

        if (clsOnlineReport.getIsChecked()) {
            itemHolder.checkbox.setImageResource(R.drawable.ic_check_box_black_24dp);
        } else {
            itemHolder.checkbox.setImageResource(R.drawable.ic_check_box_outline_blank_black_24dp);
        }

        itemHolder.parent1.setTag(position);
        itemHolder.parent2.setTag(position);

        itemHolder.parent1.setOnClickListener(this);
        itemHolder.parent2.setOnClickListener(this);

        itemHolder.time.setText(clsOnlineReport.getBulletinTime());
        itemHolder.title.setText(clsOnlineReport.getBulletinTitle());
        itemHolder.author.setText(clsOnlineReport.getCreater());
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        Collections.swap(mList, fromPosition, toPosition);
        notifyItemMoved(fromPosition, toPosition);
        return true;
    }

    class ItemHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.online_report_time)
        TextView time;
        @BindView(R.id.online_report_title)
        TextView title;
        @BindView(R.id.online_report_author)
        TextView author;
        @BindView(R.id.online_report_drag)
        ImageView drag;
        @BindView(R.id.online_report_checkbox)
        ImageView checkbox;
        @BindView(R.id.view_parent_1)
        LinearLayout parent1;
        @BindView(R.id.view_parent_2)
        LinearLayout parent2;

        ItemHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    @Override
    public void onClick(View v) {
        mCallback.onClick(v, (int) v.getTag());
    }

    public interface Callback {
        void onClick(View v, int position);
    }
}

回调接口代码:

/**
 * 用来完成RecyclerView长按拖拽的关键接口
 * 1.getMovementFlags里面表示设置为上下拖动
 * 2.onSelectedChanged里面表示拖动状态下改变背景色,拖动完成后恢复背景色
 * 3.拖动完成的时候viewHolder的值为空!!!所以要用srcHolder
 */
public class OnlineReportListCallback extends ItemTouchHelper.Callback {

    private ColorDrawable drawable;
    private RecyclerView.ViewHolder srcHolder;

    public interface ItemTouchMoveListener {
        boolean onItemMove(int fromPosition, int toPosition);
    }

    private ItemTouchMoveListener moveListener;

    public OnlineReportListCallback(ItemTouchMoveListener moveListener) {
        this.moveListener = moveListener;

        int rgb = Color.rgb(0xff, 0xff, 0xff);
        drawable = new ColorDrawable(rgb);
    }


    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {

        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        return makeMovementFlags(dragFlags, ItemTouchHelper.ACTION_STATE_IDLE);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {

        this.srcHolder = srcHolder;
        return srcHolder.getItemViewType() == targetHolder.getItemViewType() && moveListener.onItemMove(srcHolder.getAdapterPosition(), targetHolder.getAdapterPosition());
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {

        super.onSelectedChanged(viewHolder, actionState);

        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            viewHolder.itemView.setBackground(null);
        }

        if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
            srcHolder.itemView.setBackground(drawable);
        }
    }
}

实体类代码:

public class ClsOnlineReport  {

    private String bulletinID;
    private String bulletinTime;
    private String bulletinTitle;
    private String isActive;
    private String activeDate;
    private String autoCloseDate;
    private String modiManID;
    private String modiManName;
    private String orderNum;
    private String onTop;
    private String createrID;
    private String creater;
    private boolean isChecked;
    private boolean isCheckBoxVisible;

    public ClsOnlineReport() {
    }

    public String getBulletinID() {
        return bulletinID;
    }

    public void setBulletinID(String bulletinID) {
        this.bulletinID = bulletinID;
    }

    public String getBulletinTime() {
        return bulletinTime;
    }

    public void setBulletinTime(String bulletinTime) {
        this.bulletinTime = bulletinTime;
    }

    public String getBulletinTitle() {
        return bulletinTitle;
    }

    public void setBulletinTitle(String bulletinTitle) {
        this.bulletinTitle = bulletinTitle;
    }

    public String getIsActive() {
        return isActive;
    }

    public void setIsActive(String isActive) {
        this.isActive = isActive;
    }

    public String getActiveDate() {
        return activeDate;
    }

    public void setActiveDate(String activeDate) {
        this.activeDate = activeDate;
    }

    public String getAutoCloseDate() {
        return autoCloseDate;
    }

    public void setAutoCloseDate(String autoCloseDate) {
        this.autoCloseDate = autoCloseDate;
    }

    public String getModiManID() {
        return modiManID;
    }

    public void setModiManID(String modiManID) {
        this.modiManID = modiManID;
    }

    public String getModiManName() {
        return modiManName;
    }

    public void setModiManName(String modiManName) {
        this.modiManName = modiManName;
    }

    public String getOrderNum() {
        return orderNum;
    }

    public void setOrderNum(String orderNum) {
        this.orderNum = orderNum;
    }

    public String getOnTop() {
        return onTop;
    }

    public void setOnTop(String onTop) {
        this.onTop = onTop;
    }

    public String getCreaterID() {
        return createrID;
    }

    public void setCreaterID(String createrID) {
        this.createrID = createrID;
    }

    public String getCreater() {
        return creater;
    }

    public void setCreater(String creater) {
        this.creater = creater;
    }

    public boolean getIsChecked() {
        return isChecked;
    }

    public void setIsChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }

    public boolean getIsCheckBoxVisible() {
        return isCheckBoxVisible;
    }

    public void setIsCheckBoxVisible(boolean isCheckBoxVisible) {
        this.isCheckBoxVisible = isCheckBoxVisible;
    }
}

适配器布局文件代码:




    

    

    


        

        

        

        

        

    

    

    

        

        

        

        

        

    

    

    


代码有点多,但并不是很难,没有用设计模式,图片使用Android Studio内置的SVG,引入了ButterKnife绑定控件,另外内部类使用了lambda表达式折叠了,把代码在自己的IDE上面跑一遍,然后尝试修改代码,看看有什么影响,有不懂的可以问我

实现效果:


Movie201905081838_20190508190911.gif

你可能感兴趣的:(Android 实现可拖拽列表和多选功能)