简体   繁体   中英

Confused with android:width=match_parent versus wrap_content

I am trying to understand how Android layouts work. If I make a simple Linear Layout and add some Text Fields, and set the width of the Linear Layout to wrap_content, I noticed an unusual effect when changing the width of the Text Fields. If the width of the Text Field is wrap_content, then the size of the Text Field is as expected (the width of the text). However, if I set the width of the Text Field to match_parent, the size of the Text Field grows to be the width of the device screen. I expected the size of the Text View to be the width of the text, not the size of the screen display.

In other words, if the width of the parent layout is wrap_content and the width of the child view is wrap_content, then it seems the width of the child view grows to be the width of the device screen, ie the same as setting the width of the parent view to be match_parent. Can someone explain why this happens, as it seems counter intuitive to me.

Here is some simple code to illustrate what I am talking about. Change the width of the Kunal Text View from wrap_content to match_parent.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray">

    <TextView
        android:text="VIP List"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:textSize="24sp" />

    <TextView
        android:text="Kunal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:textSize="24sp" />

    <TextView
        android:text="Kagure"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:textSize="24sp" />

    <TextView
        android:text="Lyla"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:textSize="24sp" />

</LinearLayout>

make this.

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray">

You will see that "kunal" and "kagure" take all the screen's width but "Vip list" and "lyla" get the width tha it need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM