这张照片是从我当前的项目中拍摄的,但是它是用SwipeRevealLayout
创建的,所以我很难对其进行自定义。几天前,我看到了this的问题,并理解可以使用ItemTouchHelper
解决了我的问题。我找到了this代码,并试图在我的项目中使用它:
val simpleCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(p0: RecyclerView, p1: RecyclerView.ViewHolder, p2: RecyclerView.ViewHolder): Boolean {
return false
}
override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val position = viewHolder.adapterPosition
if (position != editPosition) {
if (editPosition != -1 && flagSwiped) {
adapter.notifyItemChanged(position)
flagSwiped = false
editPosition = position
}
}
return super.getSwipeDirs(recyclerView, viewHolder)
}
override fun onSwiped(holder: RecyclerView.ViewHolder, direction: Int) {
}
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
val icon: Drawable
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
val itemView = viewHolder.itemView;
val height = itemView.bottom - itemView.top;
val width = itemView.right - itemView.left;
val iconH = resources.displayMetrics.density * 28;
val iconW = resources.displayMetrics.density * 28;
if (dX > 0) {
val background = RectF(itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat())
p.color = Color.parseColor("#FF9800")
c.drawRect(background, p)
icon = ContextCompat.getDrawable(context!!, android.R.drawable.ic_input_add)!!
icon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
// you can also use icon size
// int iconWidth = icon.getIntrinsicWidth();
// int iconHeight = icon.getIntrinsicHeight();
val rate = abs(dX) / width
val iconLeft = (itemView.left - iconW + width / 3 * rate).toInt()
val iconTop = (itemView.top + height / 2 - iconH / 2).toInt()
val iconRight = (itemView.left + width / 3 * rate).toInt()
val iconBottom = (itemView.bottom - height / 2 + iconH / 2).toInt()
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
icon.draw(c)
} else if (dX < 0) {
val background = RectF(itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat())
p.color = Color.parseColor("#E91E63")
c.drawRect(background, p)
icon = ContextCompat.getDrawable(context!!, android.R.drawable.ic_menu_delete)!!
icon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
val rate = abs(dX) / width
val iconLeft = (itemView.right - width / 3 * rate).toInt()
val iconTop = (itemView.top + height / 2 - iconH / 2).toInt()
val iconRight = (itemView.right + iconW - width / 3 * rate).toInt()
val iconBottom = (itemView.bottom - height / 2 + iconH / 2).toInt()
icon.setBounds(iconLeft, iconTop, iconRight, iconBottom)
icon.draw(c)
}
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
val itemTouchHelper = ItemTouchHelper(simpleCallback)
itemTouchHelper.attachToRecyclerView(settings)
如我所见,我可以滑动recyclerview项目,但我不明白两件事: