Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering CheckBox Views

If you're interested in RadioButtons in addition to (or instead of) CheckBoxes, see this question instead.

Despite the presence of

<item name="android:layout_gravity">center_horizontal</item>

in the style file, the two checkboxes are not centered, but appear "left-justified".

non-centered

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MyLL"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/cb1"
        style="@style/CB_style" />

    <CheckBox
        android:id="@+id/cb2"
        style="@style/CB_style" />

</LinearLayout>

res/values/styles.xml

<style name="CB_style" parent="@android:style/TextAppearance.Medium">
    <item name="android:layout_gravity">center_horizontal</item>
    <item name="android:layout_weight">1</item>
    <item name="android:gravity">center</item>
    <item name="android:checked">false</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
</style>

like image 434
Calaf Avatar asked May 22 '13 17:05

Calaf


1 Answers

You have android:layout_weight = 1. So your checkboxes fill all width of screen. Remove android:layout_weight from style and add margin between checkboxes.

Gravity in Checkbox don't affect the inner tick button, only text.

EDIT

Ok, try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/MyLL"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="0dp"
        android:layout_height="5dp"
        android:layout_weight="1"/>

    <CheckBox
        android:id="@+id/cb1"
        style="@style/CB_style" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="5dp"
        android:layout_weight="1"/>

    <CheckBox
        android:id="@+id/cb2"
        style="@style/CB_style" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="5dp"
        android:layout_weight="1"/>

</LinearLayout>

And remove layout_weight from style.

Another way is create custom checkbox. But I think it's too complicated for this problem.

like image 50
Capitan Avatar answered Nov 19 '22 06:11

Capitan