Android wrap_content和fill_parent示例

在Android中,您始终将“ wrap_content ”或“ fill_parent ”放在组件的属性“ layout_width ”和“ layout_height ”上,您是否想知道有什么不同?

参见以下定义:

  1. wrap_content –该组件只希望显示足够大的内容以仅封闭其内容。
  2. 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>
android wrap-content example1

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>
android wrap-content example2

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>
android wrap-content example3

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 wrap-content example4

注意
实际上,您可以指定确切的宽度和高度,但是由于Android设备的屏幕尺寸不同,因此不建议您指定宽度和高度。 您只是不知道正在运行什么大小的Android设备。

参考文献

  1. Android XML布局文档
  2. Android ViewGroup.LayoutParams文档

翻译自: https://mkyong.com/android/android-wrap_content-and-fill_parent-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值