Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center two views within a relative layout?

The task is simple: there are two buttons and a TextView above them. All the widgets shoud be centered within the relative layout. The only one idea I have is create the third widget View and use it as a center axis for the buttons. Any ideas? A redundant layout isn't a good solution.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/app_name" />

    <View
        android:id="@+id/view_axis"
        android:layout_width="1dp"
        android:layout_height="1dp"
        android:layout_below="@id/tv_progress"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_progress"
        android:layout_toLeftOf="@id/view_axis"
        android:text="@string/start" />

    <Button
        android:id="@+id/button_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_progress"
        android:layout_toRightOf="@id/view_axis"
        android:text="@string/stop" />

</RelativeLayout>
like image 356
Maksim Dmitriev Avatar asked Jul 08 '13 15:07

Maksim Dmitriev


1 Answers

If I understand what you want correctly, you can put the Buttons in a LinearLayout and center that

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/tv_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/app_name" />
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/tv_progress">
<Button
    android:id="@+id/button_start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start" />

<Button
    android:id="@+id/button_stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stop" />
 </LinearLayout>

I'm not sure if that's what you meant by a "redundant layout" but doing this is fine if it gives you what you want.

like image 124
codeMagic Avatar answered Sep 19 '22 08:09

codeMagic