RecyclerView ItemTouchHelper Buttons on Swipe

后端 未结 11 1292
春和景丽
春和景丽 2020-11-27 11:05

I am trying to port some iOS functionality to Android.

I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.

I have

11条回答
  •  我在风中等你
    2020-11-27 11:16

    I did the following to be able to draw a drawable instead of text:

    1. In SwipeHelper, I changed

      UnderlayButton(String text, int imageResId, int color, UnderlayButtonClickListener clickListener)
      

      to

      UnderlayButton(String text, Bitmap bitmap, int color, UnderlayButtonClickListener clickListener)
      

      Of course I removed imageResId and instead created a Bitmap bitmap and passed the constructor variable to it using this.bitmap = bitmap; as the rest of the variables.

    2. In SwipeHelper.onDaw() you may then call drawBitmap() to apply your bitmap to the canvas. For example:

      c.drawBitmap(bitmap, rect.left, rect.top, p);
      

      Where c and p and your Canvas and Paint variables respectively.

    3. In the activity where I call UnderlayButton, I convert my drawable (in my case it is a VectorDrawable) to a bitmap using this method:

      int idDrawable = R.drawable.ic_delete_white;
      Bitmap bitmap = getBitmapFromVectorDrawable(getContext(), idDrawable);
      

    What remains to be done is the centring of the icon.

    Full onDraw method with text and bitmap both centered:

    public void onDraw(Canvas c, RectF rect, int pos){
                Paint p = new Paint();
    
                // Draw background
                p.setColor(color);
                c.drawRect(rect, p);
    
                // Draw Text
                p.setColor(Color.WHITE);
                p.setTextSize(24);
    
    
                float spaceHeight = 10; // change to whatever you deem looks better
                float textWidth = p.measureText(text);
                Rect bounds = new Rect();
                p.getTextBounds(text, 0, text.length(), bounds);
                float combinedHeight = bitmap.getHeight() + spaceHeight + bounds.height();
                c.drawBitmap(bitmap, rect.centerX() - (bitmap.getWidth() / 2), rect.centerY() - (combinedHeight / 2), null);
                //If you want text as well with bitmap
                c.drawText(text, rect.centerX() - (textWidth / 2), rect.centerY() + (combinedHeight / 2), p);
    
                clickRegion = rect;
                this.pos = pos;
            }
    

提交回复
热议问题