欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

仿新闻类实现滑动选择标签(二)

程序员文章站 2022-06-30 13:32:53
...

通过RecyclerView结合ItemTouchHelper实现拖动改变位置功能。
仿新闻类实现滑动选择标签(二)
标签页面主要逻辑,第一个项目不变,前一界面选择所在的标签位置,跳转到本界面,用红色文字表示,推荐栏目中,显示定制栏目不存在的栏目,删除定制栏目,添加到推荐栏目中,点击推荐栏目,将点击项加入定制栏目中,并且在推荐栏目中删除,拖动改变顺序或者添加删除后,回到前一界面,更改前一界面的标签和界面,并且定位在选中标签对应的页面。长按显示叉号

相关类:主界面
ColumnCustomizationActivity.java

public class ColumnCustomizationActivity extends BaseCompatActivity implements MyItemTouchCallback.OnDragListener
{

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.recyclerview_already)
    RecyclerView recyclerviewAlready;
    @BindView(R.id.recyclerview_recommend)
    RecyclerView recyclerviewRecommend;
    @BindView(R.id.back)
    ImageView ivBack;
    @BindView(R.id.tv_edit)
    TextView tvEdit;

    private List<ArticleBean> articleBeanList = new ArrayList<>();
    private List<ArticleBean> articleBeanList2 = new ArrayList<>();

    private RecyclerAdapter adapterAlready;
    private RecyclerAdapter adapterAll;

    private int selectPosition = 0;//与前一页对应,选中的标签

    public static String SELECT_COLUMN = "SELECT_COLUMN";
    public static String SELECT_COLUMN_INDEX = "SELECT_COLUMN_INDEX";
    private static String SELECT_PARAM = "select_column";
    private static String SELECT_PARAM_LIST = "select_column_list";
    public static void startForResult(Activity context, int selectPosition,ArrayList<ArticleBean> articleBeanArrayList, int requestCode)
    {
        Intent intent = new Intent();
        intent.setClass(context, ColumnCustomizationActivity.class);
        intent.putExtra(SELECT_PARAM, selectPosition);
        intent.putExtra(SELECT_PARAM_LIST, articleBeanArrayList);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_column_customization);
        ButterKnife.bind(this);
        ivBack.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent != null)
        {
            selectPosition = intent.getIntExtra(SELECT_PARAM, 0);
            articleBeanList= (List<ArticleBean>) intent.getSerializableExtra(SELECT_PARAM_LIST);
        }
        if(articleBeanList==null){
            articleBeanList=new ArrayList<>();
        }

        setUpRecyclerviewAlready();
        setUpRecyclerviewRecommend();

        //调用推荐栏目接口
        getListArticleMainClass();


        tvEdit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (adapterAlready != null)
                {
                    UpdateCustom();
                }
            }
        });
    }

    /**
     * 设置已选栏目
     */
    private void setUpRecyclerviewAlready()
    {
        adapterAlready = new RecyclerAdapter(R.layout.drag_item_layout, articleBeanList, false, ColumnCustomizationActivity.this, selectPosition);
        recyclerviewAlready.setHasFixedSize(true);
        recyclerviewAlready.setAdapter(adapterAlready);
        recyclerviewAlready.setNestedScrollingEnabled(false);
        //防止滑动卡顿
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3)
        {
            @Override
            public boolean canScrollVertically()
            {
                return false;
            }
        };
        recyclerviewAlready.setLayoutManager(gridLayoutManager);
        int spanCount = 3;//跟布局里面的spanCount属性是一致的
        int spacing = 10;//每一个矩形的间距
        boolean includeEdge = true;//如果设置成false那边缘地带就没有间距
        //设置每个item间距
        recyclerviewAlready.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MyItemTouchCallback(adapterAlready).setOnDragListener(this));
        itemTouchHelper.attachToRecyclerView(recyclerviewAlready);

        recyclerviewAlready.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerviewAlready)
        {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh)
            {
                tvEdit.setVisibility(View.VISIBLE);
                adapterAlready.doStartEditMode(recyclerviewAlready);
                adapterAlready.setShowImage(true);
                  if(vh.getAdapterPosition()==0){//第一项不操作
                      return;
                  }
                  itemTouchHelper.startDrag(vh);
            }

            @Override
            public void onItemClick(final RecyclerView.ViewHolder vh)
            {
                adapterAlready.setmAdapterInterface(new RecyclerAdapter.adapterInterface()
                {
                    @Override
                    public void imageViewClick()
                    {

                        try
                        {
                            articleBeanList2.add(articleBeanList.get(vh.getLayoutPosition()));
                            adapterAll.notifyDataSetChanged();
                            //点击删除按钮,如果选中的索引比剩余数据的长度大,将选中索引设置为最后一项
                            if (selectPosition == articleBeanList.size() - 1)
                            {
                                selectPosition--;
                                if (selectPosition <= 0)
                                {
                                    selectPosition = 0;
                                }
                            }
                            articleBeanList.remove(vh.getLayoutPosition());
                            adapterAlready.setSelectPosition(selectPosition);
                            adapterAlready.notifyDataSetChanged();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void itemViewClick()
                    {
                        try
                        {
                            selectPosition = vh.getLayoutPosition();//设置选中的项目
                            adapterAlready.setSelectPosition(selectPosition);
                            adapterAlready.notifyDataSetChanged();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });

                // Toast.makeText(getActivity(),item.getId()+" "+item.getName(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 设置推荐栏目
     */
    private void setUpRecyclerviewRecommend()
    {
        adapterAll = new RecyclerAdapter(R.layout.drag_item_layout, articleBeanList2, false, ColumnCustomizationActivity.this, -1);
        recyclerviewRecommend.setHasFixedSize(true);
        recyclerviewRecommend.setAdapter(adapterAll);
        recyclerviewRecommend.setNestedScrollingEnabled(false);
        //防止滑动卡顿
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3)
        {
            @Override
            public boolean canScrollVertically()
            {
                return false;
            }
        };
        recyclerviewRecommend.setLayoutManager(gridLayoutManager);

        int spanCount = 3;//跟布局里面的spanCount属性是一致的
        int spacing = 10;//每一个矩形的间距
        boolean includeEdge = true;//如果设置成false那边缘地带就没有间距
        //设置每个item间距
        recyclerviewRecommend.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MyItemTouchCallback(adapterAll).setOnDragListener(this));
        itemTouchHelper.attachToRecyclerView(recyclerviewRecommend);

        recyclerviewRecommend.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerviewAlready)
        {
            @Override
            public void onLongClick(RecyclerView.ViewHolder vh)
            {

            }

            @Override
            public void onItemClick(final RecyclerView.ViewHolder vh)
            {
                try
                {
                    //点击推荐栏目,加入到定制栏目组内,本栏目在推荐栏目组里删除,
                    articleBeanList.add(articleBeanList2.get(vh.getLayoutPosition()));
                    adapterAlready.notifyDataSetChanged();
                    articleBeanList2.remove(vh.getLayoutPosition());
                    adapterAll.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onFinishDrag()
    {

    }


    /**
     * 所有栏目
     */
    public void getListArticleMainClass()
    {

        String url = Contants.APIURL.GET_LISTARTICLEMAINCLASS.getUrl();

        RequestEntity<String> entity = new RequestEntity<>();

        OkHttpUtils.get().url(url).headers(entity.getHeader()).build().execute(new JsonCallBack<ResponseEntity<ArrayList<ArticleBean>>>()
        {
            @Override
            public void onError(Call call, Exception e, RequestCall requestCall)
            {
                ToastUtil.showLongToast("网络异常,请稍后尝试");
            }

            @Override
            public void onResponse(ResponseEntity<ArrayList<ArticleBean>> data, RequestCall requestCall)
            {
                if (data.isOK())
                {
                    articleBeanList2.clear();
                    //遍历数据,将已有的栏目筛选掉
                    for (ArticleBean bean : data.getRstData())
                    {
                        boolean isExist = false;//是否已存在栏目
                        for (ArticleBean bean1 : articleBeanList)
                        {
                            if (bean.getId().equals(bean1.getId()))
                            {
                                isExist = true;
                            }
                        }
                        if (!isExist)
                        {//不存在,添加
                            articleBeanList2.add(bean);
                        }
                    }
                    adapterAll.notifyDataSetChanged();
                }
                else
                {
                    ToastUtil.showLongToast(data.getErrorMsg());
                }
            }
        });
    }

    /**
     * 更新栏目
     */
    private void UpdateCustom()
    {
        showProgressDialog("请稍候", null, null);
        ArrayList<UpdateCustomBean> arrayList = new ArrayList<>();
        for (ArticleBean bean : articleBeanList)
        {
            UpdateCustomBean updateCustomBean = new UpdateCustomBean();
            updateCustomBean.setName(bean.getName());
            updateCustomBean.setSN(bean.getSN());
            updateCustomBean.setCitizenId("" + UserSession.getInstance().getUserInfo().getUserId());
            updateCustomBean.setClassId(bean.getId());
            arrayList.add(updateCustomBean);
        }

        RequestEntity<ArrayList<UpdateCustomBean>> entity = new RequestEntity<>();
        entity.setReqData(arrayList);

        OkHttpUtils.postString().url(Contants.APIURL.GET_UPDATECUSTOM.getUrl()).headers(entity.getHeader())
                //.mediaType(entity.getMediaType())
                .content(entity.getBody()).build().execute(new JsonCallBack<ResponseEntity<String>>()
        {
            @Override
            public void onError(Call call, Exception e, RequestCall requestCall)
            {
                dismissProgressDialog();
                ToastUtil.showLongToast("服务器繁忙,请稍后尝试。");
            }

            @Override
            public void onResponse(ResponseEntity<String> data, RequestCall requestCall)
            {
                dismissProgressDialog();

                if (data.isOK())
                {
                    selectPosition = adapterAlready.getSelectPosition();
                    Intent mIntent = new Intent();
                    mIntent.putExtra(SELECT_COLUMN, (Serializable) articleBeanList);
                    mIntent.putExtra(SELECT_COLUMN_INDEX, selectPosition);
                    ColumnCustomizationActivity.this.setResult(RESULT_OK, mIntent);
                    finish();
                }
                else
                {
                    ToastUtil.showLongToast(data.getErrorMsg());
                }
            }
        });
    }

}

activity_column_customization.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:tools="http://schemas.android.com/tools"
                                            xmlns:android="http://schemas.android.com/apk/res/android"
                                            android:layout_width="match_parent"
                                            android:layout_height="match_parent"
                                            android:background="#ffffff">
    <LinearLayout

            android:layout_width="match_parent" android:layout_height="match_parent"
            android:background="#ffffff"
            android:orientation="vertical">

        <RelativeLayout android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="10dp">
            <ImageView
                    android:id="@+id/back"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/close_new"
                    android:layout_gravity="center"
                    android:padding="10dp"
                    android:layout_centerVertical="true"
            />

            <TextView
                    android:id="@+id/toolbar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:textSize="@dimen/statebar_title_size"
                    android:textColor="@color/color_black_111111"
                    android:text="栏目定制"/>

                <TextView
                        android:id="@+id/tv_edit"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="16sp"
                        android:textColor="@color/color_black_111111"
                        android:text="完成"
                        android:visibility="invisible"
                        android:padding="10dp"
                        android:layout_centerVertical="true"
                        android:layout_alignParentRight="true"
                />


        </RelativeLayout>
        <View
                android:id="@+id/view_divider"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@color/color_gray_f4f4f4"/>
        <RelativeLayout android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:padding="10dp">
            <TextView android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textSize="16sp"
                      android:textColor="@color/black"
                      android:text="已选栏目"/>
            <TextView android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textSize="16sp"
                      android:textColor="@color/color_gray_999999"
                      android:text="按住拖动调整排序"
                      android:layout_alignParentRight="true"
                      android:layout_centerVertical="true"/>

        </RelativeLayout>
        <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview_already"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"/>
        <TextView android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="16sp"
                  android:textColor="@color/black"
                  android:text="推荐栏目"
                  android:layout_margin="10dp"/>
        <View
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@color/color_gray_f4f4f4"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"/>
        <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview_recommend"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"/>

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

drag_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="110dp"
             android:layout_height="60dp"
             android:background="@color/white"
             android:id="@+id/fragment"
            >

    <TextView
            android:id="@+id/tv_drag"
            android:layout_width="90dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:layout_margin="10dp"
            android:text="测试测试"
            android:background="@drawable/rect_solid_and_stroke_gray2_corner_5dp"
            android:textColor="@color/black"/>

    <ImageView
            android:id="@+id/iv_x"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:src="@drawable/delete_new"

    />

</FrameLayout>

MyItemTouchCallback.java

public class MyItemTouchCallback extends ItemTouchHelper.Callback {

    private ItemTouchAdapter itemTouchAdapter;
    public MyItemTouchCallback(ItemTouchAdapter itemTouchAdapter){
        this.itemTouchAdapter = itemTouchAdapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }


    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            final int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        } else {
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            //final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
            final int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
        int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
        itemTouchAdapter.onMove(fromPosition,toPosition);
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int position = viewHolder.getAdapterPosition();
        itemTouchAdapter.onSwiped(position);
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            //滑动时改变Item的透明度
            final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
            viewHolder.itemView.setAlpha(alpha);
            viewHolder.itemView.setTranslationX(dX);
        } else {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
       /* if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (background == null && bkcolor == -1) {
                Drawable drawable = viewHolder.itemView.getBackground();
                if (drawable == null) {
                    bkcolor = 0;
                } else {
                    background = drawable;
                }
            }
            viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
        }*/

        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (background == null && bkcolor == -1) {
                Drawable drawable = viewHolder.itemView.getBackground();
                if (drawable == null) {
                    bkcolor = 0;
                } else {
                    background = drawable;
                }
            }
            viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);
        }


        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);

        /*viewHolder.itemView.setAlpha(1.0f);
        if (background != null) viewHolder.itemView.setBackgroundDrawable(background);
        if (bkcolor != -1) viewHolder.itemView.setBackgroundColor(bkcolor);*/
        //viewHolder.itemView.setBackgroundColor(0);

        if (onDragListener!=null){
            onDragListener.onFinishDrag();
        }
    }

    private Drawable background = null;
    private int bkcolor = -1;

    private OnDragListener onDragListener;
    public MyItemTouchCallback setOnDragListener(OnDragListener onDragListener) {
        this.onDragListener = onDragListener;
        return this;
    }
    public interface OnDragListener{
        void onFinishDrag();
    }

    public interface ItemTouchAdapter {
        void onMove(int fromPosition, int toPosition);
        void onSwiped(int position);
    }
}

RecyclerAdapter.java

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> implements MyItemTouchCallback.ItemTouchAdapter
{

    private Context context;
    private int src;
    private List<ArticleBean> results;
    private boolean isShowImage = false;
    private adapterInterface mAdapterInterface;
    private int selectPosition = 0;//已选择栏目的位置

    public RecyclerAdapter(int src, List<ArticleBean> results, boolean isShowImage, Context context, int selectPosition)
    {
        this.results = results;
        this.src = src;
        this.isShowImage = isShowImage;
        this.context = context;
        this.selectPosition = selectPosition;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        this.context = parent.getContext();
        View itemView = LayoutInflater.from(parent.getContext()).inflate(src, parent, false);
        return new MyViewHolder(itemView);
    }

    public void setSelectPosition(int selectPosition)
    {
        this.selectPosition = selectPosition;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position)
    {
        holder.textView.setText(results.get(position).getName());
        if (position == 0&&selectPosition!=0&&selectPosition!=-1)//第一项,如果没选中,并且不等于-1(-1用来区分推荐栏目),改变颜色
        {//第一项颜色不同,不显示删除图标
            holder.imageView.setVisibility(View.INVISIBLE);
            holder.textView.setTextColor(context.getResources().getColor(R.color.color_gray_999999));
        }
        else
        {
            if (position == selectPosition)
            {//改变已选中项目背景颜色和字体颜色
              //  holder.textView.setBackgroundResource(R.drawable.rect_solid_and_stroke_red_corner_5dp);
                holder.textView.setTextColor(Color.RED);
            }
            else
            {
                holder.textView.setBackgroundResource(R.drawable.rect_solid_and_stroke_gray2_corner_5dp);
                holder.textView.setTextColor(Color.BLACK);
            }

            if (isShowImage)
            {
                holder.imageView.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.imageView.setVisibility(View.INVISIBLE);
            }
            holder.imageView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    if (mAdapterInterface != null)
                    {
                        mAdapterInterface.imageViewClick();
                    }
                }
            });

        }

        //显示删除按钮,可以点击
        if(isShowImage){
            holder.fragment.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    if (mAdapterInterface != null)
                    {
                        mAdapterInterface.itemViewClick();
                    }
                }
            });
        }

    }

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

    @Override
    public void onMove(int fromPosition, int toPosition)
    {
        if (fromPosition == 0 || toPosition == 0)
        {//第一个不可拖动
            return;
        }
        if (fromPosition < toPosition)
        {
            for (int i = fromPosition; i < toPosition; i++)
            {
                Collections.swap(results, i, i + 1);
            }
        }
        else
        {
            for (int i = fromPosition; i > toPosition; i--)
            {
                Collections.swap(results, i, i - 1);
            }
        }
        notifyItemMoved(fromPosition, toPosition);
        if(fromPosition==selectPosition){//拖动的初始位置是选中项
                selectPosition=toPosition;
        }
    }

    public int getSelectPosition()
    {
        return selectPosition;
    }

    @Override
    public void onSwiped(int position)
    {
        results.remove(position);
        notifyItemRemoved(position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder
    {

        public TextView textView;
        public ImageView imageView;
        public FrameLayout fragment;

        public MyViewHolder(View itemView)
        {
            super(itemView);
          /*  WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
            layoutParams.height = width/6;
            itemView.setLayoutParams(layoutParams);*/
            textView = (TextView) itemView.findViewById(R.id.tv_drag);
            imageView = (ImageView) itemView.findViewById(R.id.iv_x);
            fragment = (FrameLayout) itemView.findViewById(R.id.fragment);
        }
    }

    public void setShowImage(boolean showImage)
    {
        isShowImage = showImage;
    }
    public void doStartEditMode(RecyclerView parent) {
        //遍历子控件,将叉号图标显示
        int visibleChildCount = parent.getChildCount();
        for (int i = 0; i < visibleChildCount; i++) {
            View view = parent.getChildAt(i);
            ImageView imgEdit = (ImageView) view.findViewById(R.id.iv_x);
            imgEdit.setVisibility(View.VISIBLE);
        }
    }


    public boolean isShowImage()
    {
        return isShowImage;
    }

    public void setmAdapterInterface(adapterInterface mAdapterInterface)
    {
        this.mAdapterInterface = mAdapterInterface;
    }

    public interface adapterInterface
    {
        public void imageViewClick();

        public void itemViewClick();//子item点击事件
    }
}

OnRecyclerItemClickListener.java

public class OnRecyclerItemClickListener implements RecyclerView.OnItemTouchListener{
    private GestureDetectorCompat mGestureDetector;
    private RecyclerView recyclerView;

    public OnRecyclerItemClickListener(RecyclerView recyclerView){
        this.recyclerView = recyclerView;
        mGestureDetector = new GestureDetectorCompat(recyclerView.getContext(),new ItemTouchHelperGestureListener());
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        mGestureDetector.onTouchEvent(e);
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        mGestureDetector.onTouchEvent(e);
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }

    private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child!=null) {
                RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
                onItemClick(vh);
            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child!=null) {
                RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
                onLongClick(vh);
            }
        }
    }

    public void onLongClick(RecyclerView.ViewHolder vh){}
    public void onItemClick(RecyclerView.ViewHolder vh){}
}

参考文献:
android开发游记:ItemTouchHelper 使用RecyclerView打造可拖拽的GridView

相关标签: 标签 新闻