getActivity() returns null in Fragment function

后端 未结 15 1690
别那么骄傲
别那么骄傲 2020-11-22 07:28

I have a fragment (F1) with a public method like this

public void asd() {
    if (getActivity() == null) {
        Log.d(\"yes\",\"it is null\");
    }
}
         


        
15条回答
  •  感情败类
    2020-11-22 08:06

    Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)

    Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    
        Activity a;
    
        if (context instanceof Activity){
            a=(Activity) context;
        }
    
    }
    

提交回复
热议问题