Aligning drawableLeft with text of button

后端 未结 14 1967
长情又很酷
长情又很酷 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:11

    This is now available in the Material Button by default with the app:iconGravity property. However, the Material Button does not allow for setting the background to a drawable (RIP gradients).

    I converted the answers by @BobDickinson and @David-Medenjak above to kotlin and it works great.

    import android.content.Context
    import android.graphics.Canvas
    import android.util.AttributeSet
    import android.view.Gravity
    import androidx.appcompat.widget.AppCompatButton
    import kotlin.math.max
    
    class CenteredButton @JvmOverloads constructor(
      context: Context,
      attrs: AttributeSet? = null,
      defStyle: Int = R.attr.buttonStyle
    ) : AppCompatButton(context, attrs, defStyle) {
    
      init {
        gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL
      }
    
      override fun onDraw(canvas: Canvas) {
        val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()
    
        var textWidth = 0f
        layout?.let {
          for (i in 0 until layout.lineCount) {
            textWidth = max(textWidth, layout.getLineRight(i))
          }
        }
    
        val drawableLeft = compoundDrawables[0]
        val drawableWidth = drawableLeft?.intrinsicWidth ?: 0
        val drawablePadding = if (textWidth > 0 && drawableLeft != null) compoundDrawablePadding else 0
    
        val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()
    
        canvas.save()
        canvas.translate((buttonContentWidth - bodyWidth) / 2, 0f)
        super.onDraw(canvas)
        canvas.restore()
      }
    }
    

提交回复
热议问题