user2560571 user2560571 - 4 months ago 20
Android Question

how to align to right and middle in height in layout

I have a Switch, witch is aligned to the left of a layout,
I want to align a TextView to the right of it AND to the middle of the height of it.
I have done two example pictures to explain it more clearly.

This is what i have (where A is the Switch, and b is the TextView):

enter image description here

This is what i want to achieve:

enter image description here

My layout code for the switch is:

<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CIR"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:checked="true"
android:gravity="center"
android:id="@+id/newProject_switch"
android:layout_below="@+id/newProject_networkId"
android:layout_marginTop="10dp"
android:layout_alignParentLeft="true"
/>


My layout code for the TextView is:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Best Effort"
android:textSize="15dp"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/newProject_switch"
android:gravity="right|center_vertical"
android:layout_toRightOf="@+id/newProject_switch"
/>

Answer

Use this way.

Remove Extra Margin you set in your Switch and use android:gravity="center_vertical. and set TextView to android:gravity="center_vertical|right" so that it is right side and vertically center.

  <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Switch
            android:id="@+id/newProject_switch"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:checked="true"
            android:gravity="center_vertical"
            android:text="CIR" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_alignBottom="@+id/newProject_switch"
            android:layout_toRightOf="@+id/newProject_switch"
            android:gravity="center_vertical|right"
            android:text="Best Effort"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="15dp" />
    </LinearLayout>

enter image description here