Fragment的概念及使用(静态添加与动态添加碎片)
- 概念
- 案例:静态的插入碎片
- 案例:动态的插入碎片
概念
Fragment是Android3.0后引入的一个新的API,它出现的初衷是为了适应大屏幕的平板电脑,我们可以把他看成一个小型的Activity,又称Activity片段!使用Fragment 我们可以把屏幕划分成几块,然后进行分组,进行一个模块化的管理!从而可以更加方便的在运行过程中动态地更新Activity的用户界面!另外Fragment并不能单独使用,它需要嵌套在Activity 中使用,也可嵌套另一个Fragment,尽管它拥有自己的生命周期,但是还是会受到宿主Activity的生命周期的影响,比如Activity被destory销毁了,它也会跟着销毁!
案例:静态的插入碎片
把碎片放到主界面中,即activity_main中
素材:left_fragment、right_fragment、LeftFragment、RightFragment、activity_main、MainActivity
下面展示代码
left_fragment代码如下:
// 平板中左边碎片1区域
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn"
android:text="left fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
right_fragment代码如下:
// 平板中右边碎片2区域
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
android:text="right fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
LeftFragmet代码如下:
//新建的LeftFragment类必须继承自Fragment,导包时使用androidx,其它也必须使用androidx
//重写Fragment的oncreateview方法,在方法中通过解析器LayoutInflater的inflate方法将定义的左边布局动态left_fragment加载进来
package com.myapp.weixin;
import android.os.Bundle;
import android