Android之動態加載佈局
限定符的作用
由於屏幕大小的區別,平板電腦爲雙頁模式,手機爲單頁模式,使用限定符,可以在程序運行時判斷應該是使用雙頁模式還是單頁模式。
常見的限定符
分辨率限定符:
限定符 | 描述 |
---|---|
ldpi | 120 dpi 以下設備 |
mdpi | 120 dpi ~ 160 dpi 設備 |
hdpi | 160 dpi ~ 240 dpi 設備 |
xhdpi | 240 dpi ~ 320 dpi 設備 |
xxhdpi | 320 dpi ~ 480 dpi 設備 |
方向限定符:
限定符 | 描述 |
---|---|
land | 橫屏設備 |
port | 豎屏設備 |
限定符的用法:
修改FragmentTest項目中的activity_main.xml 文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
在res目錄下新建layout-large 文件夾,在這個文件夾下新建一個佈局,也叫做activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
layout/activity_main 佈局只包含了一個碎片,即單頁模式,而layout-large/
activity_main 佈局包含了兩個碎片,即雙頁模式。其中large 就是一個限定符,那些屏幕被認爲是large 的設備就會自動加載layout-large 文件夾下的佈局,而小屏幕的設備則還是會加載layout 文件夾下的佈局。
注意:將 Activity 中 replaceFragment() 方法註釋掉,因爲現在的主佈局已經沒有 right_layout
平板運行結果:
手機運行結果: