Android碎片学习(四)——动态加载布局

代码继续接上文《Android碎片学习(三)——碎片的生命周期》

对于不同分辨率的设备要用不同的布局,这就要借助限定符(Qualifiers)来实现了。

一、使用限定符

1、主布局

只留下左侧碎片并充满整个父布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.example.day06_fragment.LeftFragment"
        android:id="@+id/left_fragment"
        />
</LinearLayout>

2、大布局

res新建一个layout-large文件夹,在里面新建一个activity_main.xml布局,其中large就是一个限定符,屏幕被认为是large的设备会自动加载对应文件夹下的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.day06_fragment.LeftFragment"
        android:id="@+id/left_fragment"
        android:layout_weight="1"/>

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.day06_fragment.RightFragment"
        android:id="@+id/right_fragment"
        android:layout_weight="3"/>

</LinearLayout>

3、主活动

接下来注释掉主活动中的查看运行效果transaction.replace(R.id.right_layout, fragment);
这样对不同大小分辨率的设备会有不同的布局效果。
在这里插入图片描述

4、常见限定符

大小:smallnormallargexlarge
分辨率:ladpimdpihdpixhdpixxhdpi
方向:landport

二、使用最小宽度限定符

Smallest-width Qualifier允许我们对屏幕的宽度限定一个最小值,以这个最小值为临界点,大于这个值解加载一个布局,屏幕宽度小于这个值的设备就加载另一个布局

新建布局

res下新建一个layout-sw600dp文件夹,在里面新建一个activity_main.xml布局,这就意味着程序在屏幕宽度小于600dp的设备是默认布局,大于等于600dp用新布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.day06_fragment.LeftFragment"
        android:id="@+id/left_fragment"
        android:layout_weight="1"/>

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.day06_fragment.RightFragment"
        android:id="@+id/right_fragment"
        android:layout_weight="3"/>

</LinearLayout>
发布了156 篇原创文章 · 获赞 13 · 访问量 7227

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104069406