[关闭]
@RitcheeQinG 2020-08-25T09:08:54.000000Z 字数 1132 阅读 370

Fragment的onAttach方法

Android


很多人都建议使用fragment时从onAttach里面获取activity的引用,那么,这里获取到的activity引用是否靠谱呢?

Fragment.java

  1. void performAttach() {
  2. // ...
  3. onAttach(mHost.getContext());
  4. // ...
  5. }
  6. /**
  7. * Called when a fragment is first attached to its context.
  8. * {@link #onCreate(Bundle)} will be called after this.
  9. */
  10. @CallSuper
  11. public void onAttach(@NonNull Context context) {
  12. mCalled = true;
  13. final Activity hostActivity = mHost == null ? null : mHost.getActivity();
  14. if (hostActivity != null) {
  15. mCalled = false;
  16. onAttach(hostActivity);
  17. }
  18. }

mHost 即 FragmentHostCallback

  1. public FragmentHostCallback(@NonNull Context context, @NonNull Handler handler,
  2. int windowAnimations) {
  3. this(context instanceof Activity ? (Activity) context : null, context, handler,
  4. windowAnimations);
  5. }
  6. FragmentHostCallback(@NonNull FragmentActivity activity) {
  7. this(activity, activity /*context*/, new Handler(), 0 /*windowAnimations*/);
  8. }
  9. FragmentHostCallback(@Nullable Activity activity, @NonNull Context context,
  10. @NonNull Handler handler, int windowAnimations) {
  11. mActivity = activity;
  12. mContext = Preconditions.checkNotNull(context, "context == null");
  13. mHandler = Preconditions.checkNotNull(handler, "handler == null");
  14. mWindowAnimations = windowAnimations;
  15. }

其中,公共构造不会被使用到,所以一般情况下, context 均为 FragmentActivity 类型

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注