RELATIVE XML LAYOUT BY CODE
RELATIVE XML LAYOUT BY CODE
In Android Studio, you can design a RELATIVE XML LAYOUT BY CODE using XML code. Here’s an example of how to create a simple RelativeLayout that contains three TextView elements:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:llayout_height="wrap_content" tools:lcontext=".MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, World!" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:text="This is a RelativeLayout example." /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:text="This text is aligned to the end of the parent." /> </RelativeLayout>
This code creates a RelativeLayout that has a width of “match_parent” and a height of “wrap_content”, which means it will take up the full width of the parent container and adjust its height to fit its contents.
Inside the RelativeLayout, we have three TextView elements. Each TextView has a width of “wrap_content” and a height of “wrap_content”, which means it will adjust its size to fit its contents. The “text” attribute is used to set the text displayed in each TextView.
The key feature of RelativeLayout is the ability to position the child elements relative to one another or the parent layout. In the example above, the second TextView element is positioned “below” the first TextView element by using the layout_below attribute. The third TextView element is aligned to the “end” of the parent layout by using the layout_alignParentEnd attribute.
You can also set other attributes to adjust the layout behavior. For example, you can use layout_alignTop, layout_alignBottom, layout_alignStart, and layout_alignEnd to align the elements relative to the top, bottom, start, or end of the parent layout.
Additionally, you can also set layout_margin, layout_paddin,,g and layout_gravity attributes to adjust the position and spacing of the elements in the RelativeLayout. It’s important to note that you can add otherlayoutst or elements inside the RelativeLayout to create a nested layout. In summary, RelativeLayout is a powerful layout that allows you to arrange elements relative to one another or the parent layout. By using different attributes you can control the position and the spacing of the elements in the layout.