如果你經常使用平板電腦,應該會發現很多的平板應用現在都采用的是雙頁模式(程序會在左側的面板上顯示一個包含子項的列表,在右側的面板上顯示內容),因為平板電腦的屏幕足夠大,完全可以同時顯示下兩頁的內容,但手機的屏幕一次就只能顯示一頁的內容,因此兩個頁面需要分開顯示。
那么怎樣才能在運行時判斷程序應該是使用雙頁模式還是單頁模式呢?這就需要借助限定符(Qualifiers)來實現了。我們通過一個例子來學習一下它的用法,修改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文件夾下的布局。
在平板模擬器上重新運行程序,效果如圖所示。
再啟動一個手機模擬器,並在這個模擬器上重新運行程序,效果如圖所示。
這樣我們就實現了在程序運行時動態加載布局的功能。