getActivity() returns null in Fragment function

后端 未结 15 1851
别那么骄傲
别那么骄傲 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:18

    The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

    @Override
    public void onAttach(Context context) {
        super.onAttach(activity);
        mContext = context;
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }
    

提交回复
热议问题