Android中RecyclerView拖拽、侧删功能的实现代码

废话不多说,下面展示一下效果。

这是GridView主文件实现。

public class GridViewActivity extends AppCompatActivity { RecyclerView mRecyclerView; List<String> mStringList; RecyclerAdapter mRecyAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recyclerview); initView(); initRecy(); } private void initView() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); mRecyclerView = (RecyclerView) findViewById(R.id.view_recycler); } private void initRecy() { if (mStringList == null) { mStringList = new ArrayList<>(); } mStringList.addAll(DataManager.getData(20 - mStringList.size())); mRecyAdapter = new RecyclerAdapter(R.layout.item_gridview, mStringList, true); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4)); mRecyclerView.addItemDecoration(new DividerGriItemDecoration(this)); mRecyclerView.setHasFixedSize(true); RecyItemTouchHelperCallback itemTouchHelperCallback = new RecyItemTouchHelperCallback(mRecyAdapter, false, true); final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback); itemTouchHelper.attachToRecyclerView(mRecyclerView); mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) { @Override public void onItemClick(RecyclerView.ViewHolder viewHolder) { RecyclerAdapter.ViewHolder viewHolder1 = (RecyclerAdapter.ViewHolder) viewHolder; String tvString = viewHolder1.mTextView.getText().toString(); Toast.makeText(GridViewActivity.this, "碰了一下 " + tvString, Toast.LENGTH_SHORT).show(); } @Override public void onLongClick(RecyclerView.ViewHolder viewHolder) { RecyclerAdapter.ViewHolder viewHolder1 = (RecyclerAdapter.ViewHolder) viewHolder; String tvString = viewHolder1.mTextView.getText().toString(); Toast.makeText(GridViewActivity.this, "长按不放可以拖动!", Toast.LENGTH_SHORT).show(); if (viewHolder.getLayoutPosition() != 0) { itemTouchHelper.startDrag(viewHolder); } } }); mRecyclerView.setAdapter(mRecyAdapter); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }

代码不难理解,就是activity里面设置一大堆初始化的东西。RecyclerView 初始化,setLayoutManager、addItemDecoration、setHasFixedSize、itemTouchHelper、addOnItemTouchListener、setAdapter。拖拽效果关键代码是itemTouchHelper.startDrag(viewHolder)。其他都围绕着它来转。

然后具体看看各个设置。

DataManager

public class DataManager { private static List<String> sStringList = Arrays.asList("语文", "数学", "英语", "政治", "历史", "化学", "生物", "地理", "体育", "音乐"); public static final List<String> getData(int number) { List<String> stringList = new ArrayList<>(); for (int i = 0; i < number; i++) { stringList.add(sStringList.get(i % sStringList.size())); } return stringList; } }

DividerGriItemDecoration 这个绘画了item的边线

public class DividerGriItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; private Drawable mDivider; private int lineWidth = 1; public DividerGriItemDecoration(GridViewActivity gridViewActivity) { final TypedArray array = gridViewActivity.obtainStyledAttributes(ATTRS); mDivider = array.getDrawable(0); array.recycle(); } public DividerGriItemDecoration(int color) { mDivider = new ColorDrawable(color); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { drawHorizontal(c, parent); drawVertical(c, parent); } private void drawHorizontal(Canvas c, RecyclerView parent) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int left = child.getLeft() - params.leftMargin; final int right = child.getRight() + params.rightMargin + lineWidth; final int top = child.getBottom() + params.bottomMargin; final int bottom = top + lineWidth; mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private void drawVertical(Canvas c, RecyclerView parent) { final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getTop() - params.topMargin; final int bottom = child.getBottom() + params.bottomMargin; final int left = child.getRight() + params.rightMargin; final int right = left + lineWidth; mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, 0, lineWidth, lineWidth); } }

RecyclerAdapter 适配器,和ui建立连接

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { private int item_layout; private List<String> mDataList; private List<Integer> mInts; private boolean isFirstSpecial; public RecyclerAdapter(int item_gridview, List<String> dataList, boolean isFisrtSpecial) { this(item_gridview, dataList); this.isFirstSpecial = isFisrtSpecial; } public RecyclerAdapter(int item_gridview, List<String> dataList) { this.item_layout = item_gridview; this.mDataList = dataList; mInts = Arrays.asList(R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(item_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { String str = mDataList.get(position); if (isFirstSpecial && position == 0) { holder.itemView.setBackgroundColor(Color.LTGRAY); holder.mTextView.setText("不许动"); holder.mImageView.setImageResource(R.mipmap.ic_launcher); } else { holder.itemView.setBackgroundColor(Color.WHITE); holder.mTextView.setText(str); holder.mImageView.setImageResource(mInts.get(position % mInts.size())); } } @Override public int getItemCount() { return mDataList == null ? 0 : mDataList.size(); } public List<String> getDataList() { return mDataList; } class ViewHolder extends RecyclerView.ViewHolder { TextView mTextView; ImageView mImageView; public ViewHolder(View itemView) { super(itemView); mTextView = itemView.findViewById(R.id.tv_item); mImageView = itemView.findViewById(R.id.img_item); } } }

OnRecyclerItemClickListener,点击事件 。我们借用手势工具类GestureDetectorCompat 来操作

public abstract class OnRecyclerItemClickListener implements RecyclerView.OnItemTouchListener{ private GestureDetectorCompat mGestureDetectorCompat; private RecyclerView mRecyclerView; public OnRecyclerItemClickListener(RecyclerView mRecyclerView) { this.mRecyclerView = mRecyclerView; mGestureDetectorCompat = new GestureDetectorCompat(mRecyclerView.getContext(), new ItemTouchHelperGestureListener()); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { mGestureDetectorCompat.onTouchEvent(e); return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { mGestureDetectorCompat.onTouchEvent(e); } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } //回调事件 public abstract void onItemClick(RecyclerView.ViewHolder viewHolder); public abstract void onLongClick(RecyclerView.ViewHolder viewHolder); private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent e) { View childViewUnder = mRecyclerView.findChildViewUnder(e.getX(), e.getY()); if (childViewUnder != null) { RecyclerView.ViewHolder childViewHolder = mRecyclerView.getChildViewHolder(childViewUnder); onItemClick(childViewHolder); } return true; } @Override public void onLongPress(MotionEvent e) { View childViewUnder = mRecyclerView.findChildViewUnder(e.getX(), e.getY()); if (childViewUnder != null) { RecyclerView.ViewHolder childViewHolder = mRecyclerView.getChildViewHolder(childViewUnder); onLongClick(childViewHolder); } } } }

RecyItemTouchHelperCallback

public class RecyItemTouchHelperCallback extends ItemTouchHelper.Callback { RecyclerView.Adapter mAdapter; boolean isSwipeEnable; boolean isFirstDragUnable; public RecyItemTouchHelperCallback(RecyclerView.Adapter mAdapter) { this.mAdapter = mAdapter; isSwipeEnable = true; isFirstDragUnable = false; } public RecyItemTouchHelperCallback(RecyclerView.Adapter mAdapter, boolean isSwipeEnable, boolean isFirstDragUnable) { this.mAdapter = mAdapter; this.isSwipeEnable = isSwipeEnable; this.isFirstDragUnable = isFirstDragUnable; } // 获取Touch的响应方向 @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {//网格布局时候 int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; int swipeFlags = 0; return makeMovementFlags(dragFlags, swipeFlags); } else {//list布局时候 int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; return makeMovementFlags(dragFlags, swipeFlags); } } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); int toPosition = target.getAdapterPosition(); if (isFirstDragUnable && toPosition == 0) { return false; } //重新更新排序 if (fromPosition < toPosition) { for (int i = fromPosition; i < toPosition; i++) { Collections.swap(((RecyclerAdapter) mAdapter).getDataList(), i, i + 1); } } else { for (int i = fromPosition; i > toPosition; i--) { Collections.swap(((RecyclerAdapter) mAdapter).getDataList(), i, i - 1); } } //刷新 mAdapter.notifyItemMoved(fromPosition, toPosition); return true; } /** * 侧滑删除后会回调的方法 */ @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { int adapterPosition = viewHolder.getAdapterPosition(); mAdapter.notifyItemRemoved(adapterPosition); ((RecyclerAdapter)mAdapter).getDataList().remove(adapterPosition); } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { viewHolder.itemView.setBackgroundColor(Color.LTGRAY); } super.onSelectedChanged(viewHolder, actionState); } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setBackgroundColor(Color.WHITE); } @Override public boolean isLongPressDragEnabled() { return !isFirstDragUnable; } @Override public boolean isItemViewSwipeEnabled() { return isSwipeEnable; } }

下面是list的相关设置

同样,listview也是一顿初始化设置。

public class ListViewActivity extends AppCompatActivity { RecyclerView mRecyclerView; List<String> mStringList; RecyclerAdapter mRecyAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recyclerview); initView(); initRecy(); } private void initRecy() { if (mStringList == null) { mStringList = new ArrayList<>(); } mStringList.addAll(DataManager.getData(15 - mStringList.size())); mRecyAdapter = new RecyclerAdapter(R.layout.item_listview, mStringList); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.addItemDecoration(new DividerListItemDecoration(this, LinearLayoutManager.VERTICAL)); mRecyclerView.setHasFixedSize(true); RecyItemTouchHelperCallback itemTouchHelperCallback = new RecyItemTouchHelperCallback(mRecyAdapter); final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback); itemTouchHelper.attachToRecyclerView(mRecyclerView); mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) { @Override public void onItemClick(RecyclerView.ViewHolder viewHolder) { RecyclerAdapter.ViewHolder viewHolder1 = (RecyclerAdapter.ViewHolder) viewHolder; String tvString = viewHolder1.mTextView.getText().toString(); Toast.makeText(ListViewActivity.this, "碰了一下 " + tvString, Toast.LENGTH_SHORT).show(); } @Override public void onLongClick(RecyclerView.ViewHolder viewHolder) { Toast.makeText(ListViewActivity.this, "长按不放可以拖动!", Toast.LENGTH_SHORT).show(); } }); mRecyclerView.setAdapter(mRecyAdapter); } private void initView() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); mRecyclerView = (RecyclerView) findViewById(R.id.view_recycler); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }

DividerListItemDecoration

public class DividerListItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[] {android.R.attr.listDivider}; public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private Drawable mDivider; private int mOrientation; public DividerListItemDecoration() { super(); } public DividerListItemDecoration(Context context, int orientation) { final TypedArray array = context.obtainStyledAttributes(ATTRS); mDivider = array.getDrawable(0); array.recycle(); this.mOrientation = orientation; } public DividerListItemDecoration(Context context, int orientation, int drawableId) { mDivider = ContextCompat.getDrawable(context, drawableId); setOrientation(orientation); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } super.getItemOffsets(outRect, view, parent, state); } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientaion"); } mOrientation = orientation; } }

源码下载:http://download.csdn.net/download/loongago/9972876

总结

以上所述是小编给大家介绍的Android中RecyclerView拖拽、侧删功能的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

时间: 2024-10-01 09:34:23

Android中RecyclerView拖拽、侧删功能的实现代码的相关文章

基于jquery插件实现拖拽删除图片功能_jquery

本文实例为大家分享了jquery插件实现拖拽删除图片功能的具体代码,供大家参考,具体内容如下 实现以下效果 完全拖出这个层,图片会消失,否则图片会回到原来的位置 <html> <head> <title></title> <style type="text/css"> #mydiv{ width:900px; background-color:#444; border:1px solid red} #mydiv2{ width

Android TouchListener实现拖拽删实例代码

Android TouchListener实现拖拽删实例代码 如果为一个控件设置了该触摸监听, 控件会随着用户的拖动而移动, 如果拖动的距离大过设置的临界值, 那么当松开手指时会有回调onDragComplete, 用户可在该方法中将该控件从父布局中删除, 或这进行其他操作. 如果用户拖拽的距离小于临界值, 那么当用户松开手指时控件会回谈到原来的初始位置.这时会触发onDragRebound回调. 如果用户触摸控件之后没有拖拽而是直接松开手指, 会触发onClick回调, 这样用户就不用为该控件

js-将&amp;amp;lt;li&amp;amp;gt;拖拽到openlayers地图中,拖拽功能失效

问题描述 将<li>拖拽到openlayers地图中,拖拽功能失效 我现在有个功能,是将外部的图片拖拽到openlayers地图中.图片是用一个ztree树状菜单来显示的,利用ztree的拖拽功能将节点拖到地图中,然后在地图中生成一个图标. 在拖拽的时候,只要鼠标不进入openlayers里,拖拽功能就没问题,一旦光标进入到openlayers地图里,拖拽就好像被屏蔽了,有的时候也可以拖动到地图里,但是就好像卡主了一样,很难移动,各位js大神,有知道该怎么解决的吗?请帮忙解决一下. 解决方案

java swing中实现拖拽功能示例_java

java实现拖拽示例 Swing中实现拖拽功能,代码很简单,都有注释,自己看,运行效果如下图: 复制代码 代码如下: package com; import java.awt.*;import java.awt.datatransfer.DataFlavor;import java.awt.dnd.DnDConstants;import java.awt.dnd.DropTarget;import java.awt.dnd.DropTargetAdapter;import java.awt.dn

Android自定义可拖拽的悬浮按钮DragFloatingActionButton

悬浮按钮FloatingActionButton是Android 5.0系统添加的新控件,FloatingActionButton是继承至ImageView,所以FloatingActionButton拥有ImageView的所有属性.本文讲解的是一个实现了可拖拽的悬浮按钮,并为此添加了类似于qq的吸附边框的功能.在此之前,先了解下其简单的使用方式吧: 首先你得添加其依赖 compile 'com.android.support:design:25.3.1' 然后在布局文件中使用. <andro

掌握Dojo工具包,第4部分:Dojo中的拖拽

Dojo 支持的两种拖拽方式 在开始尝试了解实现 Dojo 拖拽效果的使用方法以前,首先必须明确拖拽具有两种截然不同的表现效果. 第一种表现效果是图标被拖拽到哪里,其就会被直接放到哪里,这个拖拽效果是图标完全紧跟拖拽的动作,与每一个拖拽动作的运动轨迹完全契合,这种效果被称为 "拖动".第二种表现效果是当图标被拖拽到一个地方,松开鼠标的时候,图标会以当前位置为基础而以其它图标为参照系进行位置的自动调整.这种效果被称为 "拖放". Dojo 的拖动 "拖动&q

Android中RecyclerView实现横向滑动代码

RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比listview更好.本文给大家介绍Android中RecyclerView实现横向滑动代码,一起看看吧. android.support.v7.widget.RecyclerView 功能:RecyclerView横向滑动 控件:<android.support.v7.widget.RecyclerView /> Java类:RecyclerView.GalleryAdap

android中集中html5,怎样实现文件下载功能,我现在有一个超链接

问题描述 android中集中html5,怎样实现文件下载功能,我现在有一个超链接 <a href="http://xxxxxxx/group1/M00/00/08/Ci09DVSb9n6AH76IAAX4AIw6xuk01.docx?attname=基于ANT的增量代码检查.docx&attachid=942'" download="基于ANT的增量代码检查.docx" class="graybtn">下载</a>

插件 放大 拖拽 旋转-求一个图片放大拖拽,旋转功能的插件!

问题描述 求一个图片放大拖拽,旋转功能的插件! 可以实现: 1,图片放大 2,可以将放大的图片拖拽 3,点击按钮左旋转和右旋转可以实现旋转操作 解决方案 bootstrap里面应该有相应的插件.