@RitcheeQinG
2020-08-25T09:08:54.000000Z
字数 1132
阅读 370
Android
很多人都建议使用fragment时从onAttach里面获取activity的引用,那么,这里获取到的activity引用是否靠谱呢?
Fragment.java
void performAttach() {
// ...
onAttach(mHost.getContext());
// ...
}
/**
* Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
@CallSuper
public void onAttach(@NonNull Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
mHost 即 FragmentHostCallback
public FragmentHostCallback(@NonNull Context context, @NonNull Handler handler,
int windowAnimations) {
this(context instanceof Activity ? (Activity) context : null, context, handler,
windowAnimations);
}
FragmentHostCallback(@NonNull FragmentActivity activity) {
this(activity, activity /*context*/, new Handler(), 0 /*windowAnimations*/);
}
FragmentHostCallback(@Nullable Activity activity, @NonNull Context context,
@NonNull Handler handler, int windowAnimations) {
mActivity = activity;
mContext = Preconditions.checkNotNull(context, "context == null");
mHandler = Preconditions.checkNotNull(handler, "handler == null");
mWindowAnimations = windowAnimations;
}
其中,公共构造不会被使用到,所以一般情况下, context 均为 FragmentActivity 类型