Aligning drawableLeft with text of button

后端 未结 14 2199
长情又很酷
长情又很酷 2021-01-30 06:41

Here is my layout:

\"enter

The issue I\'m facing is with the drawable checkmark. H

14条回答
  •  野性不改
    2021-01-30 07:08

    I started with @BobDickinson's answer, but it did not cope well with multiple lines. The approach is good, because you still end up with a Button that can properly be reused.

    Here is an adapted solution that will also work if the button has multiple lines (Please don't ask why.)

    Just extend Button and use the following in onDraw, the getLineRight() is used to look up the actual length of each line.

    @Override
    protected void onDraw(Canvas canvas) {
        // We want the icon and/or text grouped together and centered as a group.
        // We need to accommodate any existing padding
        final float buttonContentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
    
        float textWidth = 0f;
        final Layout layout = getLayout();
        if (layout != null) {
            for (int i = 0; i < layout.getLineCount(); i++) {
                textWidth = Math.max(textWidth, layout.getLineRight(i));
            }
        }
    
        // Compute left drawable width, if any
        Drawable[] drawables = getCompoundDrawables();
        Drawable drawableLeft = drawables[0];
        int drawableWidth = (drawableLeft != null) ? drawableLeft.getIntrinsicWidth() : 0;
    
        // We only count the drawable padding if there is both an icon and text
        int drawablePadding = ((textWidth > 0) && (drawableLeft != null)) ? getCompoundDrawablePadding() : 0;
    
        // Adjust contents to center
        float bodyWidth = textWidth + drawableWidth + drawablePadding;
    
        canvas.save();
        canvas.translate((buttonContentWidth - bodyWidth) / 2, 0);
        super.onDraw(canvas);
        canvas.restore();
    }
    

提交回复
热议问题