天天看点

屏幕适配全攻略(二)-- 解决方案

一、使用wrap_content、match_parent、weight

(1)、wrap_content 包裹内容

(2)、match_parent 填满父控件

(3)、layout_weight

计算出来的宽度 = 原有宽度 + 剩余控件所占百分比

举例解释:

例1:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button1"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button2"/>

</LinearLayout>
           

效果图:

屏幕适配全攻略(二)-- 解决方案

Button1:Button2 = 1:2   和weight的比例一致

计算出来的宽度 = 原有宽度 + 剩余控件所占百分比

解析:屏幕宽度L  

原有宽度:Button1 为0dp

剩余空间:L - 0   比例:1/3

Button1显示宽度:0 + (L-0)*1/3 = 1/3 L

例2:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Button1"/>
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="Button2"/>

</LinearLayout>
           
屏幕适配全攻略(二)-- 解决方案

Button1:Button2 = 2:1   和weight的比例不一致 

Why???????

计算出来的宽度 = 原有宽度 + 剩余控件所占百分比

解析:屏幕宽度L  

原有宽度:Button1 为match_parent  原有宽度为L

剩余空间:L - 2L(两个都是match_parent,所以为2L)   比例:1/3

Button1显示宽度:L + (L-2L)*1/3 = 2/3 L

同理:Button2显示宽度:1/3 L

握草原来如此:

所以以后还是老老实实的写  0dp 吧,不装逼了!!!!!!!

对于所有的View默认的权重是0,如果只设置了一个View的权重大于0,则该View将占据除去别的View本身占据的空间的所有剩余空间。

(2)、使用相对布局,禁用绝对布局(适配性太差)

(3)、使用限定符

res/layout/main.xml 单面板

res/layout-large/main.xml 多面板 屏幕大小大于7英寸 Android3.2之前

res/layout-sw600dp/mian.xml  多面板 Small Width最小宽度

但是多个进行维护不方便

未完待续。。。。

继续阅读