Loading

Fragment-静态注册

Fragment是什么

Fragment 可以做到把屏幕划分成几块,然后进行分组,进行模块化的管理。并且可以更加方便的在运行过程中动态地更新Activity的用户界面

Fragment并不能单独使用,他需要嵌套在Activity 中使用,尽管他拥有自己的生命周期,但是还是会受到宿主Activity的生命周期的影响,

比如Activity 被destory销毁了,Fragment也会跟着销毁。

之前我已经浅学了一些Fragment的知识,这次的地铁查询APP我们决定将其做的更加完善,故使用Fragment,我们决定仿照北京地铁官方app做一个底部的

导航选择栏。

Fragment的静态注册-如何静态注册一个fragment

1.首先,我们new一个新的fragment,同时还需要new一个activity,用于存放fragment

2.静态注册fragment,需要在activity中,加入<fragment/>或者<androidx.fragment.app.FragmentContainerView/>

3.你需要在代码中加入 android:name="com.example.dataapplication.fragment.xxxFragment" 关联你的fragment才行。

4.你需要在代码中加入 tools:layout="@layout/fragment_xxx" 才能让你的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"
    tools:context=".FragmentActivity"
    android:orientation="vertical">

    <fragment
        android:id="@+id/frag_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.example.dataapplication.fragment.BlankFragment1"
        tools:layout="@layout/fragment_blank1" />
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/frag_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.example.dataapplication.fragment.BlankFragment1"
        tools:layout="@layout/fragment_blank1"
        />
</LinearLayout>

 

 5.fragment中的代码,这里是默认生成的代码,我们可以根据自己的需求修改。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".fragment.BlankFragment1">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="hello_blank_fragment1"
        android:textSize="20dp"/>

</FrameLayout>

 

这就是fragment静态创建的基本方式。

posted @ 2023-03-23 01:05  冰稀饭Aurora  阅读(99)  评论(0编辑  收藏  举报