代码继续接上文《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、常见限定符
大小:small
,normal
,large
,xlarge
分辨率:ladpi
,mdpi
,hdpi
,xhdpi
,xxhdpi
方向:land
,port
二、使用最小宽度限定符
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>