目录
5.4 动态加载布局的技巧
虽然动态添加 Fragment 的功能很强大,可以解决很多实际开发中的问题,但是它毕竟只是在一 个布局文件中进行一些添加和替换操作。如果程序能够根据设备的分辨率或屏幕大小,在运行 时决定加载哪个布局,那我们可发挥的空间就更多了。因此本节我们就来探讨一下 Android 中动 态加载布局的技巧。
5.4.1 使用限定符
如果你经常使用平板,应该会发现很多平板应用采用的是双页模式(程序会在左侧的面板上显 示一个包含子项的列表,在右侧的面板上显示内容),因为平板的屏幕足够大,完全可以同时 显示两页的内容,但手机的屏幕就只能显示一页的内容,因此两个页面需要分开显示。
那么怎样才能在运行时判断程序应该是使用双页模式还是单页模式呢?这就需要借助限定符 (qualifier )来实现了。下面我们通过一个例子来学习一下它的用法,修改 FragmentTest 项目 中的 activity_main.xml 文件,代码如下所示:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/leftFrag"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent