【问题标题】:Delete item on swipe with rounded corners background使用圆角背景在滑动时删除项目
【发布时间】:2020-07-07 06:48:34
【问题描述】:

我有一个片段,其中包含带有项目的RecyclerView。我已经实现了一个“滑动删除”功能,它按预期工作。但是,我的RecyclerView 中的项目有一个带圆角的背景,而在滑动项目后面显示的背景(带有垃圾桶图标)没有圆角(见截图)。任何人都可以帮助我在那里获得圆角吗? 经过一番研究,我发现了drawRoundRect方法用于Canvas,但是,我需要这样的方法用于ColorDrawableobject。

这里是ItemTouchHelperOnChildDraw方法的代码,这里绘制了当前背景:

public class SwipeToDeleteCallback extends ItemTouchHelper.SimpleCallback {

    private RecyclerView.Adapter mAdapter;
    private Drawable icon;
    private final ColorDrawable background;
    private Context mContext;
    private Activity mActivity;
    private Fragment mFragment;


    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

        View itemView = viewHolder.itemView;
        int backgroundCornerOffset = 20;

        int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2;
        int iconBottom = iconTop + icon.getIntrinsicHeight();

        if (dX < 0) { // Swiping to the left
            int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth();
            int iconRight = itemView.getRight() - iconMargin;
            icon.setBounds(iconLeft, iconTop, iconRight, iconBottom);


            background.setBounds(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());


        } else { // view is unSwiped
            background.setBounds(0, 0, 0, 0);
        }
        background.draw(c);
        icon.draw(c);
    }
}

以及我使用drawRoundRect 方法尝试过的一些代码,但没有解决我的问题:

RectF bg = new RectF(itemView.getRight() + ((int) dX) - backgroundCornerOffset,
                    itemView.getTop(), itemView.getRight(), itemView.getBottom());
            Paint p = new Paint();
            p.setColor(Color.parseColor("#0000FF"));
            c.drawRoundRect(bg, 20, 20, p);

【问题讨论】:

    标签: java android android-recyclerview swipe rounded-corners


    【解决方案1】:

    我设法使用GradientDrawable 而不是ColorDrawable 解决了我的问题,ColorDrawable 的方法是setCornerRadius()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多