如何用android:layout_weight弄个满意的比例

如何用android:layout_weight弄个满意的比例

在布局中android:layout_width 和 android:layout_height 一般会设为wrap_content和match_parent,当再设置android:layout_weight的时候,有时候就会出现混乱

例如:

两个TextView的都为 android:layout_width = “match_parent”
“One, One”TextView的android:layout_weight = “1”
“One, Two”TextView的android:layout_weight = “2”

预测结果:

“One, One”TextView占屏幕宽的1/3
“One, Two”TextView占屏幕宽的2/3

代码:

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView

                android:text="One,One"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:id="@+id/textView11"
                android:background="@drawable/textview_border"
                android:textColor="@android:color/white"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:gravity="center"
                 />

            <TextView
                android:text="One,Two"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:id="@+id/textView12"
                android:background="@drawable/textview_border"
                android:textColor="@android:color/white"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:gravity="center"
              />

        </LinearLayout>

实际结果:
这里写图片描述
分析:

android:layout_weight = “1” 的 “One, One”TextView占屏幕的2/3
android:layout_weight = “2” 的 “One, Two”TextView占屏幕的1/3

原因:

android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!

解释:

设屏幕宽度为L,在两个TextView的宽度都为match_parent的情况下,原有宽度为L,两个的TextView的宽度都为L,那么剩余宽度为L-(L+L) = -L
“One, One” TextView的weight设置占1/3,所以总宽度是L+(-L)*1/3 = (2/3)L.
“One, Two” TextView的weight设置占2/3,所以总宽度是L+(-L)*2/3 = (1/3)L.

  • Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值