【Android】Fragment的静态动态创建以及两种创建方式的生命周期

参考:

33.3-Fragment的创建-静态创建2_哔哩哔哩_bilibili

Fragment的创建_从现有代码创建foutran-CSDN博客

【Android】Fragment的基本用法、Fragment和活动间的通信、Fragment的生命周期、动态加载布局的技巧_android fragment-CSDN博客

Fragment的静态创建

  1. 创建一个Fragment
  2. 布局代码中用一个容器承接并绑定
    1. fragment标签
    2. FragmentContainView标签

先创建一个导航界面

先创建一个带按钮的空白界面吧!

img

然后创建一个Fragment

img

创建一个Activity用来承载Fragment

由于Fragment依赖于Activity存在,故而我们首先需要创建一个Activity用来承载fragment。

Be like:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
    
    <fragment
        android:id="@+id/my_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.example.fragment.fragment.StaticFragment1"/>

</androidx.constraintlayout.widget.ConstraintLayout>

做到这一步,还并没有感觉到Fragment跟普通的Activity有什么区别,我们给fragment加点控件再看看。

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".fragment.StaticFragment1">

    <LinearLayout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值