getActivity() returns null in Fragment function

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

    Those who still have the problem with onAttach(Activity activity), Its just changed to Context -

        @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }
    

    In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -

     @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity a; //Your activity class - will probably be a global var.
        if (context instanceof mActivity){
            a=(mActivity) context;
        }
    }
    

    As suggested by user1868713.

提交回复
热议问题