通常使用权重时,layout_wight layout_height 一般设置为0. 这里讲一下宽属性设置为warp_content,再结合权重使用。
权重尺寸的计算方式
android:layout_weight的真实含义是: 那么该 View的宽度 等于 原有宽度(android:layout_width)加上剩余空间的占比!
剩余空间 = 父控件空间 - 所有子控件所需要的空间
示例一 : wight 和 match_parent 使用
设屏幕宽度为w, 两个TextView的宽度设置为match_parent, 那么它们两个view测量申请的宽度均为屏幕宽度w.
剩余宽度 = 父控件空间 - 所有子控件所需要的空间 = w - ( w + w) = -w;
第一个TextView剩余宽度 = -w * 1/3 = -1/3 w
第一个TextView宽度 = 原有宽度(android:layout_width) + 剩余空间的占比 = w + (-w * 1/3) = 2/3 w
第二个TextView宽度 = 原有宽度(android:layout_width) + 剩余空间的占比 = w + (-w * 2/3) = 1/3 w

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#fff"
android:text=" 111"
android:textSize="15dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#0a1"
android:text="222"
android:textSize="15dp" />
</LinearLayout>
示例二: wight 和 wrap_content使用
两个TextView文本内容都是1234567 , 他们测量所需要的绘制宽度为 182px, 父控件总共是300px。
剩余宽度 = 父控件空间 - 所有子控件所需要的空间 = 300px - 182px * 2 = -64px
第一个TextView宽度 = 原有宽度(android:layout_width) + 剩余空间的占比 = 182px + (-
理解Android布局权重

本文解析了Android中使用layout_weight属性的原理与技巧,通过实例展示了如何结合wrap_content和match_parent属性,实现不同场景下的灵活布局。
最低0.47元/天 解锁文章
785





