How to Show Switch widget exactly in the center of the layout?

Viewed 1622

I am trying to add switch widget in my layout. Problem i am encountering is widget appears on the right side living a space for its text(but i don't want any text. it appears like this.

enter image description here

but what i want is

enter image description here

I had tried a few ways like using nested layouts( it works well for small screen but when i try it on tabs then due to large screen it acquire more space and ultimately it shifts slightly toward right leaving space for text even though i did't entered any text).

the xml code i am currently using

   <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="3"
            android:orientation="horizontal"
            android:weightSum="11">

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="4"></LinearLayout>

            <Switch
                android:id="@+id/sosswitch"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="3"
                android:text="" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="4"></LinearLayout>


        </LinearLayout>

I am using the above code to bring the switch in middle but it still create problem in large screens.

1 Answers

Since there is no constraint to use just LinearLayout, using RelativeLayout will solve your problem.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    >

    <Switch
        android:id="@+id/sosswitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="" />

</RelativeLayout>

enter image description here

The problem was due to the extension of width of the Switch element due to the use of weight system in Linear Layout. To align the Switch in center here, layout_centerInParent is used.

Related