Fragment的Activity参考如何设置?

时间:2015-02-18 06:30:26

标签: android android-fragments

在片段source code中,它说:

// Activity this fragment is attached to.
Activity mActivity;

我希望在onAttach()中设置它,但根据来源它不是:

public void onAttach(Activity activity) {
    mCalled = true;
}

我在源中找不到设置Activity引用的位置的引用。

它在哪里设置?

3 个答案:

答案 0 :(得分:2)

FragmentManager在将moveToState附加到Fragment时处理Activity中的引用:

void moveToState(Fragment f, int newState, int transit, int transitionStyle,
        boolean keepActive) {
    ...
    if (f.mState < newState) {
    ...
        switch (f.mState) {
            case Fragment.INITIALIZING:
                ...
                f.mActivity = mActivity;
                ...
        }
    ...
}

答案 1 :(得分:1)

FragmentManager的第898行:片段生命周期的经理

答案 2 :(得分:0)

我的一个片段的摘录应该有助于回答这个问题:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // your activity IS actually given automatically to you as parameter in this overrided method... then do what you want with it...

    String activite =  activity.getClass().getSimpleName();

    if (activite.equals("HomeActivity"))
    {
        STATUS_MODE = "WHITE";
    }
    else if (activite.equals("PhoneActivity"))
    {
        STATUS_MODE = "BLACK";
    }

    // etc. etc.
}