简单探究Fragment

简单探究Fragment

Fragment是什么

Fragment (碎片)是一种可以嵌入在活动中的UI片段它能让程序更加合理和充分的利用大屏幕的空间,因此平板上应用的非常广泛。Fragment和活动非常相似,同样包含布局,有自己的生命周期。你甚至可以将碎片理解成一个迷你型的活动。

Fragment生命周期

Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。官网这张图很好的说明了两者生命周期的关系:
这里写图片描述
可以看到Fragment比Activity多了几个额外的生命周期回调方法:
onAttach():当Fragment与Activity发生关联时调用。
onCreateView():创建该Fragment的视图
onActivityCreated():当Activity的onCreate方法返回时调用
onDestoryView():与onCreateView想对应,当该Fragment的视图被移除时调用
onDetach():与onAttach相对应,当Fragment与Activity关联被取消时调用

介绍完Fragment,现在我们来讲一讲它的应用

Fragment的应用

Fragment静态加载怎么用

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中。

下面展示一个例子(我使用2个Fragment作为Activity的布局):

FirstFragment的布局文件:

<?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"
    android:background="#999999"
    tools:context=".test.FirstFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My Firat Fragment"
        android:textSize="30dp"
        android:gravity="center"/>

</FrameLayout>

SecondFragment的布局文件:

<?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"
    android:background="#f9c3c3"
    tools:context=".test.SecondFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My Second Fragment"
        android:textSize="30dp"
        android:gravity="center" />

</FrameLayout>

两个fragment用不同颜色,便于区分

Activity的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".test.TestActivity">

    <fragment
        
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值