我有一个RecyclerView,刷完后应删除这些项目。我用ItemTouchHelper类解决了它。在onChildDraw方法中,我设置了一个红色背景,在刷新列表项后面时出现。最重要的是,右侧网站上有一个垃圾桶图标。它工作正常,但是如果你开始滑动并且不要滑到最后然后再刷回到正常位置,垃圾的图标就不会消失。但是,当我滑动所选项目时,它只会消失,而不是正常项目。
以下是ItemTouchHelper类的代码:
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
rvAdapter.removeItem(position);
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive){
Bitmap icon;
if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
View itemView = viewHolder.itemView;
float height = (float) itemView.getBottom() - (float) itemView.getTop();
float marginRight = 10;
paint.setColor(Color.parseColor("#D32F2F"));
RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom());
c.drawRect(background,paint);
icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_delete_forever);
RectF icon_dest = new RectF((float) itemView.getRight() - marginRight - height, itemView.getTop(), itemView.getRight() - marginRight, itemView.getBottom());
c.drawBitmap(icon,null,icon_dest,paint);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
有人知道如何在取消滑动时删除图标?还是有类似z-index的东西?因为当我向后滑动所选项目时,垃圾桶图标会在项目下消失。但是当我刷一个普通项目时,图标就在项目上方,然后图标就会停留在那里。
答案 0 :(得分:0)
@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) {
Bitmap icon;
Paint paint = new Paint();
View itemView = viewHolder.itemView;
float height = (float) itemView.getBottom() - (float) itemView.getTop();
float width = height / 3;
if (dX < 0) {
paint.setColor(Color.parseColor("#D32F2F"));
RectF background = new RectF(
(float) itemView.getRight() + dX, (float) itemView.getTop(),
(float) itemView.getRight(), (float) itemView.getBottom());
c.drawRect(background, paint);
icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_delete);
RectF iconDest = new RectF(
(float) itemView.getRight() - 2 * width, (float) itemView.getTop() + width,
(float) itemView.getRight() - width, (float) itemView.getBottom() - width);
c.drawBitmap(icon, null, iconDest, paint);
}
} else if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
final float alpha = ALPHA_FULL - Math.abs(dY) / (float) viewHolder.itemView.getHeight();
viewHolder.itemView.setAlpha(alpha);
viewHolder.itemView.setTranslationY(dY);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}