最近打算找工作,所以回头复习了一下基础,随便巩固一下知识。所以有问题的话欢迎一起讨论。
今天的主角是Layout_weight 我想大家都知道这个属性的作用吧,那就是设置该控件在父控件所占的比重。下面看一下最基本的用法
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Aaaaaaaaaaaaaaaaaaa" />
<Button
android:id="@+id/btn1"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="A" />
<Button
android:id="@+id/btn2"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content"
android:text="A" />
</LinearLayout>
给大家看一下效果图
我想细心的人发现了,当我们的text值太多时候设置权重(layout_weight)并没有对齐!!!
疑问一:为什么没有对齐?疑问能能不能对齐?
答:
一:其实这里只是控件没有对齐,对齐的是第一行文字,是因为在
LinearLayout中会默认设置baselineAligned属性为true;baselineAligned这个属性名为基准线(大家不了解这个熟悉的可以去查看相关文档),类似英语中的第三条横线。
二:回答了一,二就非常简单了:把baselineAligned设置为false(这个属性是在LinearLayout中)
面试回答:这里的没有对齐的是控件,对齐的是第一行文本,原因是因为LinearLayout控件默认设置baselineAligned为true,只需修改baselineAligned为false就可以对齐控件了
下面我们修改一下代码:
把子控件android:layout_width="0dp"改为
android:layout_width="wrap_content"看一下代码和效果
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Aaaaaaaaaaaaaaaaaaa" />
<Button
android:id="@+id/btn1"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="A" />
<Button
android:id="@+id/btn2"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content"
android:text="A" />
</LinearLayout>

???这是为什么?设置android:layout_weight权重属性怎么没有起作用?
答:在LinearLayout控件中会先给android:layout_width="wrap_content"会优先分配子控件大小,因为这里的第一个button的text内容较多,所以先满足了button1 剩下的在按照权重分配