zoukankan      html  css  js  c++  java
  • 关于weight属性使用的一些细节

    之前被这个属性困扰过好久,今天一个偶然的机会,终于把这个搞清楚了,现在与大家分享一下。

    假设我们要在一个LinearLayout布局中显示两个按钮,button1和button2,button2的宽度是button1的二倍,正常情况下使用weight应该是这样的:

    <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:orientation="horizontal" >
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="button1" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="button2" />
    
    </LinearLayout>

    注意两个button的宽都是0dp

    效果图:
    这里写图片描述

    可是如果换一种方式:

    <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:orientation="horizontal" >
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="button1" />
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="button2" />
    
    </LinearLayout>

    两个button的宽度都是match_parent,情况立马发生转变:
    这里写图片描述

    我以前就在这里不知道纠结了多少回,那么我们到底该怎么理解weight这个属性呢?

    设置了weight属性的View的宽度等于原有宽度加上剩余空间的占比,其中剩余空间是指屏幕宽度相对于控件总宽度剩余的空间大小。

    以第一种情况为例


    假设屏幕宽度为L,第一个button原有宽度是0dp,那么该button的宽度为0+(L-0)×1/3 = (1/3)L
    其中(L-0)中,L表示屏幕宽度,0表示两个控件的总宽度


    以第二种情况为例


    假设屏幕宽度为L,因为两个都是match_parent,所以总宽度是2L,那么对于第一个button而言,它的宽度为:L+(L-2L)×1/3 = (2/3)L
    其中(L-2L)中,L表示屏幕宽度,2L表示两个控件的总宽度


    总结:建议大家在使用weight属性的过程中把相应的宽或者高设置为0dp,这也是Google推荐的做法。水平排列的话宽设置为0dp,竖直排列的话高设置为0dp.

  • 相关阅读:
    其它人的面试
    面试准备——(一)测试基础(3)测试用例的编写
    面试准备——(三)Selenium(1)基础问题及自动化测试
    HTTP简介,http是一个属于应用层的面向对象的协议
    fidder(介绍)
    软件测试基础知识大全
    为什么要走川藏线(人文版)(转)
    将Windows 8.1 系统窗口背景设置成淡绿色?
    如何看待淘宝二手交易APP“闲鱼”推出的新功能“闲鱼小法庭”?
    轻轻松松种绿豆
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461758.html
Copyright © 2011-2022 走看看