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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值