I have a CheckBox
that I want centered within its own boundaries, not pushed to the side. Probably easier demonstrated than explained:
Note that it isn't centered. Currently defined as:
<CheckBox
android:id="@+id/checkbox_star"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:button="@drawable/btn_favorite"
android:layout_gravity="center"
android:minWidth="48dp" />
Nevermind the custom button drawable. It behaves the same with a vanilla CheckBox
as well (the small check box behaves the same).
I believe the problem is that the Checkbox widget uses a regular TextView with the
drawableLeft
attribute, because it expects text to be shown as well. (This is why you see it centered vertically, but offset slightly to the left.)If you simply want an image button with multiple states, I suggest using a ToggleButton with your custom images in a state list selector. Or you could create a custom class that extends ImageView and implements Checkable.
Just use following approach:
It works well for me. But it works only for
You can use a parent layout to achieve this :
This will work correct as need required. Just small changes in background and button attributes. This code snippet is tested successfully. Hope this helps.
I'm using
MaterialCheckBox
frommaterial-components-android
(orAppCompatCheckBox
. They're similar).I find that if a CheckBox doesn't have any text, setting its
android:minWidth="0dp"
andandroid:minHeight="0dp"
can remove all paddings and center the drawable.This align problem can be solved by CheckableImageView, a custom
View
that extendImageView
orAppCompatImageView
and implementCheckable
directly. It also have otherImageView
attributes.Just set your selector drawable in src property of your XML and the drawable state of check will follow automatically.
Example of use
Selector example(put inside drawable folder with extension
.xml
)Change ic_cb_check and ic_cb_uncheck with your preferred images.
This code also available at https://gist.github.com/hendrawd/661824a721c22b3244667379e9358b5f