In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to theright of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment (Right of Login button parallely)
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to theright of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment (Right of Login button parallely)
Example code snippet
< Button android:id = "@+id/btnLogin" ..></ Button > < Button android:layout_toRightOf = "@id/btnLogin" android:layout_alignTop = "@id/btnLogin" ..></ Button >
Here are the steps to create a relative layout
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “relative_layout.xml” res/layout -> Right Click -> New -> Android XML File 3. Now open newly created xml file (in my case “relative_layout.xml”) and type the following code. <? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "fill_parent" android:layout_height = "wrap_content" > < TextView android:id = "@+id/label" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "Email" /> < EditText android:id = "@+id/inputEmail" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:layout_below = "@id/label" /> < Button android:id = "@+id/btnLogin" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@id/inputEmail" android:layout_alignParentLeft = "true" android:layout_marginRight = "10px" android:text = "Login" /> < Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_toRightOf = "@id/btnLogin" android:layout_alignTop = "@id/btnLogin" android:text = "Cancel" /> < Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentBottom = "true" android:text = "Register new Account" android:layout_centerHorizontal = "true" /> </ RelativeLayout >
To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created relative layout in the emulator.
|
No comments:
Post a Comment