Introduction

LayoutParams are used by views to tell their parents how they want to be laid out. The base LayoutParams class just describes how big the view wants to be for both width and height. To specify how big a view must be we use android:layout_width and android:layout_height attributes. The values of these attributes can either one of the following

  • fill_parent
  • match_parent
  • wrap_content
  • An exact number

From API level 8 (Android 2.2) functionally no difference between fill_parent and match_parent, . FILL_PARENT is still available for compatibility reason. LayoutParams.FILL_PARENT and LayoutParams.MATCH_PARENT both have value -1.

 

match_parent

When you set layout width and height as match_parent, it will occupy the complete area that the parent view has, i.e. it will be as big as the parent. If parent is applied a padding then that space would not be included.

Consider below example, parent is red and child is green. Child occupy all area because it’s width and height are match_parent. If parent is applied a padding then that space would not be included for the child.

<!-- #1 Parent with no padding -->
<LinearLayout
  android:layout_width="300dp"
  android:layout_height="300dp"
  android:background="#f9b0b0">

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b0f9dc"/>

</LinearLayout>

<!-- #2 Parent with padding -->
<LinearLayout
  android:layout_width="300dp"
  android:layout_height="300dp"
  android:background="#f9b0b0"
  android:paddingTop="20dp"
  android:paddingBottom="10dp">

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b0f9dc"/>
</LinearLayout>

 

Below image shows the rendered layout of the above code

 

wrap_content

Setting a View’s size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains i.e. view wants to be just big enough to enclose its content (plus padding) .

Consider below layout, sub-view LinearLayout does not occupy any space as there is noting that it holds that has to be displayed. If we add a Button to the LinearLayout with width and height as “wrap_content”. You would see that now the LinearLayout occupies space as that required by the button to be displayed.

<RelativeLayout
  android:layout_width="300dp"
  android:layout_height="300dp"
  android:background="#f9b0b0">

  <LinearLayout
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"/>
</RelativeLayout>