android UI界面 weight 用法

android UI界面 weight 用法

:android

-weight用在xml
- 语句为android:layout_weight=”数字”
- 主要用在LinearLayout布局中markdown


weight能够理解为权重,(控件)按比例占据空间的意思,这个空间通常来讲是线性(横或者竖)的。

例如,在方向为horizontal 的LinearLayout中,有个TextView和EditText

代码为:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">



    <TextView  android:layout_width="0dp" android:layout_height="50dp" android:textSize="25dp" android:gravity="center" android:text="姓名" android:layout_weight="1"/>


    <EditText  android:layout_width="0dp" android:layout_height="50dp" android:hint="请输入姓名" android:ems="10" android:id="@+id/editText1" android:layout_weight="1" />
</LinearLayout>

代码相应的图

**

上图中,左边的TextView和右边的EditText各占了这一行空间的 1/2,正分别对应了代码中的android:layout_weight=”1” (1+1=2,分别占比例1/2)


同理,若左边控件android:layout_weight=“4”,则左边空间占4/5,右边控件占1/5 ,以下图

这里写图片描述

注意:上述这些都是在全部控件的width设置为0dp或者match_parent前提下。

若width设置为具体大于0的数值(例如50dp)或wrap_content。则效果相反,能够理解为weight为权重优先级,数值越小,占比例越大,即左边的控件weight为4时,占1/5,而右边的占4/5

为了方便直观,因此在用weight的时候,控件统一width设置为0dp就行

相关文章
相关标签/搜索