Android Fragment的用法(二)

 如果你经常使用平板电脑,应该会发现很多的平板应用现在都采用的是双页模式(程序会在左侧的面板上显示一个包含子项的列表,在右侧的面板上显示内容),因为平板电脑的屏幕足够大,完全可以同时显示下两页的内容,但手机的屏幕一次就只能显示一页的内容,因此两个页面需要分开显示。

那么怎样才能在运行时判断程序应该是使用双页模式还是单页模式呢?这就需要借助限定符(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文件夹下的布局。

  在平板模拟器上重新运行程序,效果如图所示。

     

  再启动一个手机模拟器,并在这个模拟器上重新运行程序,效果如图所示。

     

  

  这样我们就实现了在程序运行时动态加载布局的功能。

 转载https://www.cnblogs.com/guop/p/5072740.html

原文地址:https://www.cnblogs.com/Jeely/p/11043631.html