您的位置:首页 > 移动开发 > Android开发

Android开发笔记—— layout_weight

2015-06-17 13:17 411 查看
在我们日常开发中,LinearLayout是我们经常用到的布局组件,其中有一个属性layout_weight属性在我们的布局屏幕适配中起了很重要作用,但是当设置这一属性以后,再设置组件宽度会出现不同的状况:

当组件宽度设置为match_parent时:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="ok1sssssss" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="ok2" />

</LinearLayout>


效果是这样



显示结果正好是2:1 跟我们设置的权值相反

当我们把宽度设置为warp_content时:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="ok1sssssss" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="ok2" />

</LinearLayout>


效果如下:



在我刻意将button1的文字加长以后,加上权值以后,最终效果近似于1:1的效果。

那么问题来了,这个权值到底是不是比例,我们应该怎么样来使用它?

在这里weight的实际含义其实是:

一旦该组件指定了weight属性,那么该组件的宽度就等于该组件宽度(layout_width)加上剩余空间所占比

设屏幕宽度为L,在两个view的宽度都为match_parent的情况下,原有宽度为L,两个的View的宽度都为L,那么剩余宽度为L-(L+L) = -L, 左边的View占比三分之一,所以总宽度是L+(-L)*1/3 = (2/3)L.所以出现为什么权重为0.5的反而长度为权重为1的两倍,而在warp_content中,权重为0.5的字符串长度长一些,最终效果就类似一比一。

实际上,谷歌推荐的方法就是在使用权重属性时,将该组件的宽度设为0,然后得到的效果就是和权重比相匹配的效果:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="ok1sssss" />

<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="ok2" />

</LinearLayout>




结论:当我们使用layout_weight属性的时候,需要将组件的宽度或高度(看父类标签是横向还是纵向)设置为0dp,此时组件就是按照权重比来确定大小的,这在屏幕适配中非常常见
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: