Fragment

Fragment的生命周期和状态

img

img

onCreateView()onViewCreated()的区别

  1. onCreateView()返回的就是fragment要显示的view;

  2. onViewCreated()onCreateView()执行完后立即执行。

一个完整的Android Activity和fragment的生命周期对比

img

方法描述
onAttach()托管Fragment到Activity中,绑定Fragment
onCreate()创建Fragment时调用,初始化一段资源文件
onCreateView()在Fragment首次绘制其用户界面时调用。从该方法中返回的 View 必须是Fragment布局的根视图。如果Fragment未提供 UI,返回 null。
onViewCreated()在Fragment被绘制后,调用此方法,可以初始化控件资源。
onActivityCreated()
onStart()
onResume()
onPause()此方法作为用户离开Fragment的第一个信号(但并不意味着此Fragment会被销毁)
onStop()
onDestroyView()Fragment中的布局被移除时调用。
onDestory()
onDetach()解绑Fragment

Fragment使用

静态用法

  1. 继承Fragment,重写onCreateView()决定Fragment的布局
  2. 在Activity中声明此Fragment,就当和普通的View一样
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_use_confirm, container, false);
}

动态用法

public class MainActivityextendsActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display display = getWindowManager().getDefaultDisplay();
        if (display.getWidth() > display.getHeight()) {
            Fragment1 fragment1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
        } else {
            Fragment2 fragment2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
        }
    }

首先,获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:

  1. 获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到;
  2. 开启一个事务,通过调用beginTransaction方法开启;
  3. 向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例;
  4. 提交事务,调用commit方法提交。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kopppoooooo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值