Android——面试题之Layout_weight

最近打算找工作,所以回头复习了一下基础,随便巩固一下知识。所以有问题的话欢迎一起讨论。

今天的主角是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 剩下的在按照权重分配

总结:在android:layout_weight属性时:view在绘制权重比例时候会优先分配android:layout_width所占用的大小,当分配的android:layout_width大小时候已经等于或者超过父控件大小时候android:layout_weight会失效,如果小于父控件的大小,再将剩下的尺寸按照权重分配,即:

android:layout_weight分配的大小=(父控件大小-android:layout_width)*权重比例大小

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容