android studio 創建的默認布局代碼是這樣的:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.jcwn888.adtest.SecondActivity"> </android.support.constraint.ConstraintLayout>
注意到代碼中加粗的部分,是ConstraintLayout,這個布局里的元素設置match_parent會失效,當你切換到Design視圖后,match_parent會自動變為固定尺寸xxx dpi(如下圖),還增加幾行亂七八糟的屬性設置,運行后也會發現元素的尺寸並沒有依父級布局變化。

其中Button標簽出現了紅下划線,錯誤信息如下:

This View is not constraints, it only has designtime positions, so it will jump to (0,0) unless you add constraints......
大概意思是,ConstraintLayout這個布局允許你把元素放到任意位置,他會自動記錄元素的絕對位置和尺寸,不支持隨時變化的樣式(比如match_parent)
所以呢,解決辦法是,拋棄ConstraintLayout,變為LinearLayout
把布局代碼改為這個樣子:
<?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="match_parent"> <Button android:id="@+id/button_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 1"/> </LinearLayout>
里面的Button的寬度就可以設置為match_parent了
