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

android 屏幕适配攻略(2) weight 注意点

2016-07-05 17:50 399 查看
使用weight控制两个按钮在水平方向 1:2

  水平方向:layout_width = "0dp"

  使用weight属性

<?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"
android:orientation="horizontal" >

<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />

<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="Button2" />

</LinearLayout>


稍作改变:将layout_width = "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"
android:orientation="horizontal" >

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="Button2" />

</LinearLayout>


两者效果对比



只是改变了layout的值, 导致两种显示不同

控件的实际宽度如何计算:

宽度 = 原来宽度 + 剩余宽度的百分比;

通俗来说的是:

  宽度 = layout_weight定义的宽度 + (屏幕宽度 - 两个组件layout_weight的宽度)* 百分比

假设屏幕宽度为L

对于layout_width = "0dp"

  button1 : = 0dp + (L-0dp-0dp)* 1/3 = 1/3L

  button2 : = 0dp + (L - 0dp - 0dp) * 2/3 = 2/3L

layout_width="match_parent"的话 原来宽度为L

  button1 = L + (L - (L+L))*1/3 = L - 1/3L = 2/3L

  button2 = L + (L -(L+L))*2/3 = L - 2/3L = 1/3L
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: