Android中的getActivity()方法

  /**
    * 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();
}

返回一个和此fragment绑定的FragmentActivity或者其子类的实例(即和当前碎片相关联的活动实例)。相反,如果此fragment绑定的是一个context的话,可能会返回null。因为getActivity()大部分都是在fragment中使用到,而fragment需要依赖于activity,所有我们在fragment里头需要做一些动作,比如启动一个activity,就需要拿到activity对象才可以启动,而fragment对象是没有startActivity()方法的。

这个方法主要是用来进行碎片和活动之间的通信。

posted @ 2020-09-26 17:47  模糊计算士  阅读(3554)  评论(0编辑  收藏  举报