简体   繁体   English

Android:从Activity调用片段函数,该片段函数包含getActivity()并返回null

[英]Android: Call fragment functions from Activity, the fragment function contains getActivity() and returns null

I have a fragment as follows: 我有一个片段,如下所示:

public class F1 extends Fragment {

    ...
    public void function1 (){
        activity = getActivity();
    }

}

When trying to call this function in the activity which has this fragment, 当尝试在具有此片段的活动中调用此函数时,

public class Activity1 extends Activity {

    private F1 f1 = new F1();
    f1.function1();

}

it returns null . 它返回null

How can I solve this problem? 我怎么解决这个问题? Can anyone provide a working code example? 谁能提供一个有效的代码示例?

It returns null because the fragment didn't attach to the Activity. 它返回null,因为该片段未附加到Activity。 so use Fragment Manager to access Fragments and also you can use Activity Context in onAttach(Activity activity) , and it would be for sure not Null. 因此,请使用“片段管理器”来访问片段,并且您也可以在onAttach(Activity activity)中使用“活动上下文”,这肯定不是Null。

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    this.activityContext = activity; //then use activity context
}

and for getting your Fragment Instance : 和获取您的片段实例:

F1 f1 = (F1) getFragmentManager().findFragmentByTag(F1.TAG_FRAGMENT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM