Fragment创建完成后并不能单独使用,还需要将Fragment加载到Activity中,在Activity中添加Fragment的方式有两种:静态加载和动态加载,接下来分别进行学习。
一、静态加载
静态加载Fragment非常简单,直接把Fragment当成普通的控件写在Activity的布局文件中。使用<fragment></fragment>标签,该标签与其他控件的标签类似,但必须要指定android:name属性或class属性,其属性值为Fragment的全路径名称。
接下来在上一期的案例基础上继续学习,首先修改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="vertical">
<fragment
android:id="@+id/fragment_one"
android:name="com.jinyu.cqkxzsxy.android.fragmentsample.FirstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
当然,也可以这样使用:
<?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="vertical">
<fragment
android:id="@+id/fragment_one"
class="com.jinyu.cqkxzsxy.android.fragmentsample.FirstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
上面两种方法选择其中一种即可,然后在Activity在onCreate( )方法中调用setContentView()加载布局文件即可。默认已经加载activity_main布局,这里就不做修改。
这样我们的第一个Fragment示例程序就已经完成了。直接运行程序,可以看到下图所示界面:
二、动态加载
已经学会了在布局文件中添加Fragment的方法,非常简单,但是有一个缺点,那就是一旦添加就不能在运行时将其删除。所以我们还可以通过动态加载的方式来完成,这种方式是在运行时添加,相对来说比较灵活。
首先Activity需要有一个ViewGroup容器存放Fragment,一般使用FrameLayout。
继续在Activity对应的activity_main布局文件中加入FrameLayout,再次修改后的代码如下:
<?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="vertical">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
然后在Activity中,通过代码将Fragment添加进Activity中。动态添加Fragment主要分为4步:
-
获取到FragmentManager对象,在V4包中通过getSupportFragmentManager方法获取,在系统中原生的Fragment是通过getFragmentManager获得的。
-
开启一个事务,通过调用beginTransaction方法开启。