What is the function of wrap_content?

1
    RelativeLayout onCreateLayout = new RelativeLayout(this);
    onCreateLayout.setBackgroundColor(Color.CYAN);

    RelativeLayout.LayoutParams ClickMeParms = new RelativeLayout.LayoutParams  (
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
            );

    ClickMeParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
    ClickMeParms.addRule(RelativeLayout.CENTER_VERTICAL);
    
asked by anonymous 22.06.2017 / 14:13

2 answers

5

WRAP_CONTENT is a property that defines the height or width) of the view based on its content. This value indicates that the size of this element should fit the content assigned to it.

See an example below, in which the height of LinearLayout will be proportional to the size of the view Button :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
>
    <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Button"
 />
</LinearLayout>

In other words, you should only occupy the space you need (height and / or width) to display your information in the layout.

See this little illustration below in which the orange mark represents a LinearLayout with property wrap_content at the height in the left image and match_parent in the right image.

    
22.06.2017 / 14:35
0

It is intended to inform you that the view or layout should be sized enough to show all its content, including any paddind .

How it works.

The layout design is processed in two passages: "measuring" and "positioning".

Each of the passages runs through the "views tree" from the top to the bottom. During the "measurement" pass each view in the "tree" informs its size specifications and calculates its size. At the end all views have their dimensions saved.

The "measurement" pass uses the ViewGroup.LayoutParams class to communicate dimensions. It is used by "children" objects to tell "parents" how they want to be measured and positioned. The ViewGroup.LayoutParams base class only describes how large the view wants to be for both width and height.

For each dimension, it specifies one of the following values:

  • An exact number.
  • MATCH_PARENT, which means that the view wants to be as big as the parent (less padding )
  • WRAP_CONTENT means that the view wants to be large enough to include its content (more padding ).

During the "positioning" pass each "parent" view is responsible for positioning each "child" using the calculated sizes in the "measurement" passage.

    
22.06.2017 / 14:36