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

android中weight的使用

2016-04-09 10:38 453 查看
在xml布局中一不小心写了这样一个布局..

<?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="match_parent"
android:orientation="horizontal" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="@string/btn2"/>
</LinearLayout>


我原来想实现的是button_1所占比例为1,button_2所占比例为2.

可结果为:



原来button所占的宽度是这样计算的:计算出来的宽度=按钮设置的宽度+剩余空间所占百分比宽度。

则第一个button的宽度为:L+(L-2L)*1/3=2/3L。

第二个button的宽度为:L+(L-2L)*2/3=1/3L。

要达到我们所需要的效果,即这样修改:

<?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="match_parent"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn1"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="@string/btn2"/>
</LinearLayout>


就能达到button_1所占比例为1,button_2所占比例为2;

修改后第一个button的宽度:0+L*1/3=1/3L;

小知识,怕以后会忘掉~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  布局 android