Fragment getActivity详解

Fragment getActivity详解

  • 首先先来看下官网对getActivity解释:
  • public final Activity getActivity ()
  • Return the Activity this fragment is currently associated with.
  • 返回此fragment当前与之关联的Activity。

接下来我们对源码角度来分析getActivity

在日常开发中 在FragmentActivity 中调用 getSupportFragmentManager() 来进行fragment 管理,这里我们先看下 FragmentActivity源码如下:

在FragmentActivity 中调用getSupportFragmentManager() 

public class FragmentActivity extends BaseFragmentActivityJB {

//创建 FragmentController 并 new HostCallbacks()父类就是FragmentHostCallback()
final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
//创建createController 并需要传 FragmentHostCallback对象
public static final FragmentController createController(FragmentHostCallback callbacks) {
    return new FragmentController(callbacks);
}
// new HostCallbacks() 并通过 super(FragmentActivity.this /*fragmentActivity*/);
//将当前FragmentActivity.this 传给FragmentHostCallback
class HostCallbacks extends FragmentHostCallback {
   public HostCallbacks() {
      super(FragmentActivity.this /*fragmentActivity*/);
   }
}

//通过 super(FragmentActivity.this /*fragmentActivity*/)
FragmentHostCallback(FragmentActivity activity) {
    this(activity, activity /*context*/, activity.mHandler, 0 /*windowAnimations*/);
}
//mActivity 赋值
//mContext activity强转Context
//mHandler 获取activity.mHandler 
FragmentHostCallback(Activity activity, Context context, Handler handler,
        int windowAnimations) {
    mActivity = activity;
    mContext = context;
    mHandler = handler;
    mWindowAnimations = windowAnimations;
}
//mHost 是 FragmentHostCallback 调用 FragmentHostCallback.getFragmentManagerImpl()
public FragmentManager getSupportFragmentManager() {
    return mHost.getFragmentManagerImpl();
}
这里我们看到FragmentActivity 启动完成后会创建FragmentController.createController(new HostCallbacks()) 并需要传HostCallbacks()是继承FragmentHostCallback()通过 super(FragmentActivity.this /*fragmentActivity*/) 将FragmentActivity.this传给FragmentHostCallback() 并执行四个参数的构造方法 分别给mActivity 赋值,将mActivity强转 mContext并赋值mContext,获取mActivity的mHandler并赋值给mHandler,第四个参数是0

.我们在Fragment中调用getActivity()

//在fragment 中调用getActivity()
// Activity this fragment is attached to.
FragmentHostCallback mHost;
final public Activity getActivity() {
    return mHost == null ? null : mHost.getActivity();
}

最后 fragment 中调用getActivity() 这个mHost 就是我们上面说的FragmentHostCallback()是在启动FragmentActivity启动并创建FragmentController.createController(new HostCallbacks());进行赋值的,所以说getActivity() 就是获取当前正在加载fragment的Activity.

你可能感兴趣的:(Fragment getActivity详解)