Android layout_width属性解释(附实例)

1,174 阅读2分钟

Androidlayout_width 属性用于定义你在布局中的视图元素的基本宽度。

宽度可以用任何有效的尺寸量度来指定 (dp,in,mm,pt,sp,px)

或者你也可以使用特殊的常数来指定宽度:match_parentwrap_content

让我们看看layout_width 属性的一些实际例子。

下面的代码将一个TextView 的宽度定义为300px

<TextView
 android:layout_width="300px"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!" />

上面的代码将在你的布局中产生以下输出:

Android layout_width specific size

Android layout_width specific size

上面的TextView 元素的宽度将被固定为300px

你也可以根据内容的大小,使用wrap_content 值来设置宽度值的扩展或收缩,如下所示:

<TextView
 android:layout_width="wrap_content"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!" />

wrap_content 值将扩大TextView 元素的宽度,以包住该元素的内容。

你在该元素中设置的任何填充也将被考虑在内。

下面的例子显示了如何在一个TextView 元素中使用wrap_content 值:

<TextView
 android:layout_width="wrap_content"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!"/>

结果将是这样的:

Android layout_width as wrap_content

Android layout_width as wrap_content

你可以为你的视图添加水平围栏,如下所示:

<TextView
 android:layout_width="wrap_content"
 android:paddingHorizontal="30dp"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!"/>

Android layout_width as wrap_content with padding

Android layout_width as wrap_content with padding

使用wrap_content 常数,Android会尝试将你的视图的layout_width 属性设置为跟随你的视图内容的长度。

你也可以使用match_parent 常数将视图的宽度设置为跟随视图的父元素的宽度。

match_parent 常数将使用父元素的宽度**,不包括父元素的填充**。

请看下面的例子:

<TextView
android:layout_width="match_parent"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!"/>

TextView 的宽度应该与父元素相匹配,如下图所示:

Android layout_width as match_parent

Android layout_width as match_parent

如果父元素有paddings,那么视图的宽度将被padding的值所减少。

在下面的代码中,LinearLayout 的水平padding为50dp

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
 android:paddingHorizontal="50dp"
 tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:background="@color/teal_200"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>

上面的代码将产生以下输出:

Android layout_width as match_parent with padding

Android layout_width as match_parent with padding

正如你所看到的,父元素中的paddings将减少视图的宽度。

而这就是android:layout_width 属性的作用。你可以尝试为该属性设置各种值,看看它对你的Android视图的作用。