material-components / material-components-android

Modular and customizable Material Design UI components for Android
Apache License 2.0
16.3k stars 3.06k forks source link

[MaterialRadioButton] App centerIfNoTextEnabled like checkboxes #3301

Open nicbell opened 1 year ago

nicbell commented 1 year ago

Is your feature request related to a problem? Please describe.

By default MaterialCheckBox will center if there is no content using the centerIfNoTextEnabled property. Oddly this was never added for MaterialRadioButton

<com.google.android.material.radiobutton.MaterialRadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<com.google.android.material.checkbox.MaterialCheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
image image

Describe the solution you'd like A clear and concise description of what you want to happen.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

We also happily accept pull requests.

nicbell commented 1 year ago

Copying the onDraw method from checkbox fixes it.

class MaterialRadioButton2@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : MaterialRadioButton(context, attrs, defStyleAttr) {

    override fun onDraw(canvas: Canvas) {
        // Horizontally center the button drawable and ripple when there's no text.
        if (TextUtils.isEmpty(text)) {
            val drawable: Drawable? = CompoundButtonCompat.getButtonDrawable(this)
            if (drawable != null) {
                val dx = (width - drawable.intrinsicWidth) / 2
                val saveCount: Int = canvas.save()
                canvas.translate(dx.toFloat(), 0f)
                super.onDraw(canvas)
                canvas.restoreToCount(saveCount)
                if (background != null) {
                    val bounds: Rect = drawable.bounds
                    DrawableCompat.setHotspotBounds(
                        background, bounds.left + dx, bounds.top, bounds.right + dx, bounds.bottom
                    )
                }
                return
            }
        }
        super.onDraw(canvas)
    }
}
image image