在Android中,您始终将“ wrap_content
”或“ fill_parent
”放在组件的属性“ layout_width
”和“ layout_height
”上,您是否想知道有什么不同?
参见以下定义:
- wrap_content –该组件只希望显示足够大的内容以仅封闭其内容。
- fill_parent –组件要显示与其父对象一样大的元素,并填充剩余空间。 (在API级别8中重命名为match_parent)
以上条款现在可能没有意义,让我们看下面的演示:
1. wrap_content
一个按钮组件,在width和height属性上均设置“ wrap_content
”。 它告诉Android将按钮显示得足够大以仅将其内容“ 按钮ABC ”括起来。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button ABC"/>
</RelativeLayout>
2. fill_parent –宽度
将“ layout_width
”更改为“ fill_parent
”,现在,按钮的宽度将填充剩余的空间,与父级“ RelativeLayout
”一样大,但是按钮的高度仍然足够大,只能包围它的内容。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button ABC"/>
</RelativeLayout>
3. fill_parent –高度
将“ layout_height
”更改为“ fill_parent
”,现在,按钮的高度将填充剩余的空间,与父级“ RelativeLayout
”一样大,但是按钮的宽度仍然足够大以仅包含其内容。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Button ABC"/>
</RelativeLayout>
4. fill_parent –宽度,高度
将“ layout_width
”和“ layout_height
”都更改为“ fill_parent
”,该按钮将显示与整个设备屏幕一样大,仅填充整个屏幕空间。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/btnButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Button ABC"/>
</RelativeLayout>
注意
实际上,您可以指定确切的宽度和高度,但是由于Android设备的屏幕尺寸不同,因此不建议您指定宽度和高度。 您只是不知道正在运行什么大小的Android设备。
参考文献
翻译自: https://mkyong.com/android/android-wrap_content-and-fill_parent-example/