Android之BaseFragment的封装(第一篇)

Fragment的生命周期:在这里插入图片描述在这里插入图片描述

onCreateView是创建的时候调用,onViewCreated是在onCreateView后被触发的事件(重点)

BaseFragment封装的Demo:

package com.example.shoppingmall.base;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
作用:基类Fragment
//  首页:HomeFragment
//  分类:TypeFragment
//  发现:CommunityFragment
//  购物车:ShoppingCartFragment
//用户中心:UserFragment
//等都要继承该类

public abstract class BaseFragment extends Fragment {
    //上下文对象
    public Context mContext;
    //当该类被系统创建的时候被回调
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    //子Fragment的UI创建
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView();
    }

    //抽象类,由孩子实现,实现不同效果
    protected abstract View initView();

    //当Activity被创建了的时候回调这个方法
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    //当子类需要联网请求数据的时候,可以重写该方法,在该方法中联网请求
    public void initData() {
    }
}

其中关于上下文对象获取getActivity()[mContext = getActivity()]源代码解释:

一个Fragment必须被嵌入到一个Activity中,它的生命周期直接受其所属的宿主Activity的生命周期影响

/**
     * Return the {@link FragmentActivity} this fragment is currently associated with.
     * May return {@code null} if the fragment is associated with a {@link Context}
     * instead.
     *
     * @see #requireActivity()
     */
    @Nullable
    final public FragmentActivity getActivity() {
        return mHost == null ? null : (FragmentActivity) mHost.getActivity();
    }

    /**
     * Return the {@link FragmentActivity} this fragment is currently associated with.
     *
     * @throws IllegalStateException if not currently associated with an activity or if associated
     * only with a context.
     * @see #getActivity()
     */
    @NonNull
    public final FragmentActivity requireActivity() {
        FragmentActivity activity = getActivity();
        if (activity == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to an activity.");
        }
        return activity;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值