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了