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

Android布局中权重设置问题

2015-10-15 10:17 411 查看
现在Android中最为推荐的屏幕适应方案即为设置控件的权重weight,一般用于线性布局中。传统的 layout_weight 使用方法是将当前控件的 layout_width 和 layout_height都设置成 fill_parent, 这样就可以把控件的显示比例完全交给 layout_weight ;这样使用的话,就出现了 layout_weight 越小,显示比例越大的情况。不过对于 2 个控件还好,如果控件过多,且显示比例也不相同的时候,控制起来就比较麻烦了,毕竟反比不是那么好确定的。 于是就有了现在最为流行的 0px 设值法。看似让人难以理解的layout_height=0px 的写法,结合 layout_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"
tools:context=".MainActivity"
android:orientation="horizontal"
android:weightSum="3"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:showDividers="middle">

<fragment
android:layout_width="0px"
android:layout_height="match_parent"
android:name="com.ztsoft.wzy.fragmentstest.BooklistFragment"
android:id="@+id/fragment"
android:layout_weight="1" />

<fragment
android:layout_width="0px"
android:layout_height="match_parent"
android:name="com.ztsoft.wzy.fragmentstest.BookFragment"
android:id="@+id/fragment2"
android:layout_weight="2" />

</LinearLayout>
两个控件会显示为1:2的大小,但是此处有一点需指出,这个权重受所在布局的控制,LinearLayout属性中的weightsum控制其所属控件的weight的值的和的最大取值。如:weight取值3,两个控件分别取值1和2,若取值2和2,则控件就会超出屏幕的大小,出现异常。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: