我使用的是RecyclerView
,我已设法使用以下代码实现Swipe to Delete:
@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) {
// Get RecyclerView item from the ViewHolder
View itemView = viewHolder.itemView;
canvas = c;
Paint p = new Paint();
Bitmap icon;
if (dX > 0) {
icon = BitmapFactory.decodeResource(
activity.getResources(), R.drawable.ic_delete_white_36dp);
/* Set your color for positive displacement */
p.setARGB(255, 255, 0, 0);
// Draw Rect with varying right side, equal to displacement dX
c.drawRect((float) itemView.getLeft(), (float) itemView.getTop(), dX,
(float) itemView.getBottom(), p);
// Set the image icon for Right swipe
c.drawBitmap(icon,
(float) itemView.getLeft() + HelperMethods.dpToPixel(16),
(float) itemView.getTop() + ((float) itemView.getBottom() - (float) itemView.getTop() - icon.getHeight()) / 2,
p);
} else {
icon = BitmapFactory.decodeResource(
activity.getResources(), R.drawable.ic_delete_white_36dp);
/* Set your color for negative displacement */
p.setARGB(255, 255, 0, 0);
// Draw Rect with varying left side, equal to the item's right side
// plus negative displacement dX
c.drawRect((float) itemView.getRight() + dX, (float) itemView.getTop(),
(float) itemView.getRight(), (float) itemView.getBottom(), p);
//Set the image icon for Left swipe
c.drawBitmap(icon,
(float) itemView.getRight() - HelperMethods.dpToPixel(16) - icon.getWidth(),
(float) itemView.getTop() + ((float) itemView.getBottom() - (float) itemView.getTop() - icon.getHeight()) / 2,
p);
}
Integer ALPHA_FULL = 255;
// Fade out the view as it is swiped out of the parent's bounds
final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationX(dX);
}
}
用户刷过项目后,我在几秒钟内无法实施UNDO选项。
我希望它看起来与gmail app undo选项类似,我想不使用任何外部库。
答案 0 :(得分:2)
我猜你有一个onSwiped
方法,你从适配器中删除项目?我的建议是不要在那里删除它,只需将其标记为刷掉即可。您的适配器和视图持有者应该在onChildDraw中显示与您的绘图相同的视图。你有一个撤销按钮,所以如果用户点击它只是将swiped off flag设置为false并重绘该行(我的意思是通知适配器来做)。在onSwiped
启动一个计时器,如果在x毫秒内没有任何反应,实际上从适配器中删除该项。
编辑:这只是一个想法,实际上从未这样做过......
编辑:我对此有所了解,请参阅此blog post和此github repo。