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).
The only proper solution is to add insets to the image. Most of the solutions with "foreground" won't work below API 23.
btn_favorite_inset.xml
in drawable dirYour layout file
Do not use this code to bypass checkbox bug with center aligment for >SDK23 if you are going to use checkboxes in recyclerview.
Checkboxes will not get checked in onBindViewHolder until next refresh if RV (example: scroll,..).
In your code, you have set the height of checkbox to match_parent. Set it to wrap_content. This will solve your problem. Worked for me!
Problem:
Solution:
Set the
android:width
so that it only shows your checkbox, then center it usingandroid:layout_gravity="center"
.I have tried j__m's answer above, and it works, but not good enough.
In my case, I wanted to add paddings around the CheckBox's drawable, in order to increase the touch area. And j__m's answer makes it hard to adjust the UI.
I think a better solution is to create an inset drawable to wrap your original state drawable, which should be very easy and work perfectly.