Saturday, May 25, 2013

Lesson 6. Android Wrap_content And Match_parent

Android Wrap_content And Match_parent

Android Wrap_content And Match_parent

In Android, while designing layout you always put either "wrap_content" or "match_parenton component’s attribute on "layout_width" and "layout_height",  did any one know what’s the different?

  1. wrap_content – The component just want to display big enough to enclose its content only.
  2. fill_parent – The component want to display as big as its parent, and fill in the remaining spaces. (renamed match_parent in API Level 8)

1. wrap_content

A button component, set "wrap_content" on both width and height attribute. It tell Android to display the button big enough to enclose it’s content “Button Hello World” only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





2. match_parent – width

Change the "layout_width" to "match_parent", now, the button’s width will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s height is still big enough to enclose it’s content only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





3. match_parent – height

Change the "layout_height" to "match_parent", now, the button’s height will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s width is still big enough to enclose it’s content only.


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

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>




4. match_parent – width, height

Change the both "layout_widthand "layout_height" to "match_parent", the button will display as big as the whole device screen, it just fill in the entire screen space.

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

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>

No comments:

Post a Comment