android_ItemTouchHelper的使用(实现板块筛选功能)

代码直接copy 需要compile

butterknife 以及 commonAdapter

效果图

android_ItemTouchHelper的使用(实现板块筛选功能)

layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_item_touch_helper"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.iamchan.allfunction.ui.widget.ItemTouchHelperActivity">
    <include layout="@layout/toolbar"></include>
    <RelativeLayout
        android:layout_marginRight="12dp"
        android:layout_marginLeft="12dp"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:textSize="15sp"
            android:layout_centerVertical="true"
            android:id="@+id/name"
            android:text="我的板块"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/edit_btn"
            android:textColor="@color/red"
            android:textSize="12sp"
            android:background="@drawable/itemtouchhelperactivity_bianji"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:text="编辑"
            android:layout_width="55dp"
            android:layout_height="30dp" />

        <TextView
            android:visibility="invisible"
            android:textSize="13sp"
            android:layout_marginLeft="10dp"
            android:id="@+id/an"
            android:text="长按可以排序"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/name" />
    </RelativeLayout>

    <View
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@color/gray"
        android:layout_width="match_parent"
        android:layout_height="1dp"></View>
    <android.support.v7.widget.RecyclerView
        android:overScrollMode="never"
        android:scrollbars="none"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="5dp"
        android:id="@+id/recyc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

    <LinearLayout
        android:layout_marginTop="5dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="35dp">

        <TextView
            android:textSize="15sp"
            android:layout_gravity="center_vertical"
            android:text="板块推荐"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <View
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@color/gray"
        android:layout_width="match_parent"
        android:layout_height="1dp"></View>

    <android.support.v7.widget.RecyclerView
        android:overScrollMode="never"
        android:scrollbars="none"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="5dp"
        android:id="@+id/recyc2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>
</LinearLayout>

item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_margin="5dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:background="@color/white"
            android:gravity="center"
            android:text="头条" />

        <ImageView
            android:id="@+id/x"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:layout_alignParentRight="true"
            android:src="@mipmap/x"
            android:visibility="invisible" />
    </RelativeLayout>
</LinearLayout>

java:

@BindView(R.id.iv_imgLeft)
ImageView ivImgLeft;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.edit_btn)
Button editBtn;
@BindView(R.id.recyc)
RecyclerView recyc;
@BindView(R.id.recyc2)
RecyclerView recyc2;
@BindView(R.id.an)
TextView an;

private int btnTag;

private List<String> recycList;
private List<String> recyc2List;
private CommonAdapter comm;
private CommonAdapter comm2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_touch_helper_test);
    ButterKnife.bind(this);
    tvTitle.setText("itemTouchHelper");
    ivImgLeft.setImageResource(R.drawable.left);
    ivImgLeft.setVisibility(View.VISIBLE);
    initData();
    initRecyc();
}

private void initData() {
    recycList = new ArrayList<>();
    recycList.add("头条");
    recycList.add("科技");
    recycList.add("市场");
    recycList.add("项目");
    recyc2List = new ArrayList<>();
    recyc2List.add("行情");
    recyc2List.add("曝光");
    recyc2List.add("行情");
    recyc2List.add("海外");
    recyc2List.add("政策");
    recyc2List.add("专家");
    recyc2List.add("活动");
    recyc2List.add("专题");

}

private void initRecyc() {

    comm=new CommonAdapter(this,R.layout.item_itemtouchhelperactivity_industry,recycList) {
        @Override
        protected void convert(final ViewHolder holder, Object o, final int position) {
            holder.setText(R.id.name,recycList.get(position));
            /*
            * 右上角标的显示与隐藏
            * */
            if(btnTag==1){
                holder.getView(R.id.x).setVisibility(View.VISIBLE);
            }else{
                holder.getView(R.id.x).setVisibility(View.GONE);
            }
            /*
            * item第0条数据不需要显示角标
            * */
            if(position==0){
                holder.getView(R.id.x).setVisibility(View.GONE);
            }
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(btnTag==1) {
                        if(position!=0) {
                            /*
                            * 这里面实现交换数据
                            * */
                            recyc2List.add(recycList.get(holder.getAdapterPosition()));
                            comm2.notifyDataSetChanged();
                            recycList.remove(holder.getAdapterPosition());
                            comm.notifyDataSetChanged();
                        }
                    }
                }
            });
            /*
            * 长按操作
            * */
            holder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    editBtn.setText("完成");
                    btnTag = 1;
                    an.setVisibility(View.VISIBLE);
                    comm.notifyDataSetChanged();
                    comm2.notifyDataSetChanged();
                    return true;
                }
            });

        }
    };
    recyc.setAdapter(comm);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
    recyc.setLayoutManager(gridLayoutManager);


    comm2=new CommonAdapter(this,R.layout.item_itemtouchhelperactivity_industry,recyc2List) {
        @Override
        protected void convert(final ViewHolder holder, Object o, int position) {
            holder.setText(R.id.name,recyc2List.get(position));
            if(btnTag==1){
                holder.getView(R.id.x).setVisibility(View.VISIBLE);
            }else{
                holder.getView(R.id.x).setVisibility(View.GONE);
            }
            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(btnTag==1) {
                        /*
                        * 这里面实现交换数据
                        * */
                        recycList.add(recyc2List.get(holder.getAdapterPosition()));
                        comm.notifyDataSetChanged();
                        recyc2List.remove(holder.getAdapterPosition());
                        comm2.notifyDataSetChanged();
                    }
                }
            });
        }
    };
    recyc2.setAdapter(comm2);
    GridLayoutManager gridLayoutManager2 = new GridLayoutManager(this, 4);
    recyc2.setLayoutManager(gridLayoutManager2);
    /*
    * 使用itemTouchCallBack的时候
    * */
    ItemTouchCallBack itemTouchCallBack=new ItemTouchCallBack(recycList,comm);
    ItemTouchHelper itemTouchHelper=new ItemTouchHelper(itemTouchCallBack);
    itemTouchHelper.attachToRecyclerView(recyc);

}


@OnClick({R.id.iv_imgLeft, R.id.edit_btn})
public void onViewClicked(View view) {
    switch (view.getId()) {
        case R.id.iv_imgLeft:
            finish();
            break;
        case R.id.edit_btn:
            if(btnTag==0) {
                an.setVisibility(View.VISIBLE);
                editBtn.setText("完成");
                btnTag=1;
                comm.notifyDataSetChanged();
                comm2.notifyDataSetChanged();
            }else{
                an.setVisibility(View.GONE);
                editBtn.setText("编辑");
                btnTag=0;
                comm.notifyDataSetChanged();
                comm2.notifyDataSetChanged();
            }
            break;
    }
}

itemTouchCallBack:

public class ItemTouchCallBack extends ItemTouchHelper.Callback {

    private List<String> strings;
    private CommonAdapter recycAdapter;


    /*
    *构造方法
    * */
    public ItemTouchCallBack(List<String> strings, CommonAdapter recycAdapter) {
        this.strings = strings;
        this.recycAdapter = recycAdapter;
    }

    /*
    * 1.Should return a composite flag which defines the enabled move directions in each state(idle, swiping, dragging)
    * 应该返回一个复合标志,该标志定义了每个状态中启用的移动方向(空闲、滑动、拖动)
    * 2.Instead of composing this flag manually, you can use {@link #makeMovementFlags(int,int)} or {@link #makeFlag(int, int)}.
    * 您可以使用{@link #makeMovementFlags(int,int)}或{@link #makeFlag(int, int)}。
    * 3.This flag is composed of 3 sets of 8 bits, where first 8 bits are for IDLE state, next 8 bits are for SWIPE state and third 8 bits are for DRAG state.
    *他的标志由3组8位组成,前8位表示空闲状态,下一个8位为滑动状态,第三个为拖动状态。
    * 4.makeMovementFlags 大体意思就是传进去两个值 第一个值为拖拽的方向 第二个值为滑动的方向
    *  源码
       * Convenience method to create movement flags.
         * <p>
         * For instance, if you want to let your items be drag & dropped vertically and swiped
         * left to be dismissed, you can call this method with:
         * <code>makeMovementFlags(UP | DOWN, LEFT);</code>
         *
         * @param dragFlags  The directions in which the item can be dragged.
         * @param swipeFlags The directions in which the item can be swiped.
         * @return Returns an integer composed of the given drag and swipe flags.

      public static int makeMovementFlags(int dragFlags, int swipeFlags) {
        return makeFlag(ACTION_STATE_IDLE, swipeFlags | dragFlags)
                | makeFlag(ACTION_STATE_SWIPE, swipeFlags)
                | makeFlag(ACTION_STATE_DRAG, dragFlags);
    }*/

    /*
    *
    * 这个方法主要是 确定一个标识  这个标识能让你的recyclerView实现拖拽和滑动的效果  这里面主要是实现拖拽的效果
    * 这个方法返回的是一个复合标志 可以使用makeMovementFlags(int,int)或makeFlag(int, int)作为返回对象
    * 上面是源码中看到的
    *
    * */
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        return makeMovementFlags(dragFlags, 0);
    }
    /*
    * 1.Called when ItemTouchHelper wants to move the dragged item from its old position to the new position.
    *  当ItemTouchHelper希望将拖动的项目从原来的位置移动到新位置
    * 2.If this method returns true, ItemTouchHelper assumes {@code viewHolder} has been moved to the adapter position of {@code target} ViewHolder
    * 如果该方法返回true, ItemTouchHelper假设{@code viewHolder}已被移动到{@code target} ViewHolder的适配器位置  也就是true能移动 false不能移动
    * */


    /*
    *
    * 这个方法主要是从旧位置移动到一个新位置 下面这个方法就是移动位置交换数据
    * 上面是源码解释
    *
    * */
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int fromPosition = viewHolder.getAdapterPosition();//从哪个位置移动的
        int toPosition = target.getAdapterPosition();//移动到哪个位置
        if (fromPosition != 0 && toPosition != 0) {
            if (fromPosition < toPosition) {//判断交换数据位置
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(strings, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(strings, i, i - 1);
                }
            }
            recycAdapter.notifyItemMoved(fromPosition, toPosition);
        }
        return true;
    }

    /*
    * Called when a ViewHolder is swiped by the user.
    * 这个方法滑动时调用
    * */
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    }
   /*
   *
   * 1.Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed.
   * 当被ItemTouchHelper滑动或拖动的ViewHolder更改时调用
   * */

    /*
    * 这个方法主要是实现开始拖拽的时候实现放大效果
    * actionState 有三种 ACTION_STATE_IDLE,ACTION_STATE_SWIPE  or ACTION_STATE_DRAG
    * */
    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        super.onSelectedChanged(viewHolder, actionState);
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            viewHolder.itemView.setScaleX(1.2f);
            viewHolder.itemView.setScaleY(1.2f);
        }
    }

    /*
    *Called by the ItemTouchHelper when the user interaction with an element is over and it also completed its animation.
    * 当用户与元素的交互结束并结束时,ItemTouchHelper调用它也完成了动画
    * */

    /*
    * 这个方法结束时调用  对应上面的onSelectedChanged方法
    * */
    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setScaleX(1.0f);
        viewHolder.itemView.setScaleY(1.0f);
    }
    /*
    * 是否启用长按脱拽
    * */
    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    /*
    * 是否启用滑动
    * */
    @Override
    public boolean isItemViewSwipeEnabled() {
        return false;
    }

}