今天在学习第二行代码的时候遇到一个问题,在碎片化的这一节有一个动态加载布局。所谓动态加载布局就是为了兼容手机和平板尺寸上的大一不一。使用动态加载布局的方式程序会根据设备的分辨率或者屏幕大小在运行的时候进行判断来加载哪一个布局。先看实现效果:
手机:
平板:
实现方法就是有2个activity_main.xml文件,一个在res/layout/下面,一个在res/large/下面。
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context="com.example.tony.fragmenttest.MainActivity">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.tony.fragmenttest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--<!–<fragment
android:id="@+id/right_fragment"
android:name="com.example.tony.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"–>
android:layout_weight="1" />-->
<!-- <FrameLayout
android:id="@+id/right_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
</FrameLayout>-->
</LinearLayout>
res/large/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.tony.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.tony.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
使用最小宽度限定符这一个需要新建一个layout-sw600dp的文件夹来存放xml文件,一开始自己折腾好久发现在这个文件夹下面无法新建layout布局文件,后来才发现是文件名称输入错误了,中间的分隔符不是下划线_,而是-。就是layout_se600dp跟layout-sw600dp的区别。所以敲代码这个东西还是需要仔细,不然一个符号一个字母打错都会让我们找半天错误而又发现不了哪里错了。然后在这个文件夹下面新建activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.tony.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.tony.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
这样当程序运行在屏幕宽度大于600的设备就会加载这个布局文件,反之则会加载res/layout/activity_main.xml这个布局文件。