天天看點

螢幕适配全攻略(二)-- 解決方案

一、使用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最小寬度

但是多個進行維護不友善

未完待續。。。。

繼續閱讀