• 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文件夹下的布局。

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

         

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

         

      

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

  • 相关阅读:
    Django 之 admin管理工具
    第二十七天- 网络通信协议 TCP UDP 缓冲区
    第二十六天- C/S架构 通信流程 socket
    第二十五天- 包
    第二十四天- 模块导入 import from xxx import xxx
    第二十三天- 模块 re
    第二十二天- 序列化 pickle json shelve
    第二十一天- 基本模块
    第二十天- 多继承 经典MRO 新式MRO super()
    第十九天- 约束 异常处理 日志使用
  • 原文地址:https://www.cnblogs.com/guop/p/5072740.html
Copyright © 2020-2023  润新知