Matin Baki
Matin Baki

Reputation: 31

Relative Layout In Android - Centerof

In a Relative View Group, we can place one view above or below another view: "layout_above" and "layout_below." etc...

Now, the problem I have is that if I want to position one view in the center of another view (not necessarily in the center of the parent), what should I do?

Like This

Of course, it can be implemented using margins, but it doesn't provide a precise fix and can be quite annoying...

Upvotes: 0

Views: 43

Answers (3)

Matin Baki
Matin Baki

Reputation: 31

This method gives me the answer to my question (based on "Douglas Jones's" help).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="30dp"
    >
    <TextView
        android:id="@+id/View_1"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:text="View_1"
        android:textSize="30dp"
        android:gravity="center"
        android:background="@color/color_red"/>

    >
    <FrameLayout
        android:layout_below="@id/View_1"
        android:layout_alignStart="@id/View_1"
        android:layout_alignEnd="@id/View_1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        > 

    <TextView
        android:layout_gravity="center"
        android:layout_below="@id/View_1"
        android:layout_toLeftOf="@id/View_1"
        android:layout_toRightOf="@id/View_1"
        android:id="@+id/View_2"
        android:layout_width="60dp"
        android:layout_height="100dp"
        android:text="View_2"
        android:gravity="center"
        android:background="@color/color_blue"/>
    </FrameLayout>
    

</RelativeLayout>

Here

Upvotes: 0

Douglas Jones
Douglas Jones

Reputation: 2542

You want layout_alignLeft and layout_alignRight which will make the boundaries match those of the referenced view

   <TextView
    android:id="@+id/View_2"
    android:layout_below="@id/View_1"
    android:layout_alignLeft="@id/View_1"
    android:layout_alignRight="@id/View_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="View_2"
    android:gravity="center"
    android:background="@color/color_blue"/>

Upvotes: 0

Hossein
Hossein

Reputation: 479

<...
android:id="@id/View_2"
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/View_1"
android:layout_toRightOf="@+id/View_1"
..../>

Upvotes: 0

Related Questions