getActivity() returns null in Fragment function

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

    You can using onAttach or if you do not want to put onAttach everywhere then you can put a method that returns ApplicationContext on the main App class :

    public class App {
        ...  
        private static Context context;
    
        @Override
        public void onCreate() {
            super.onCreate();
            context = this;
        }
    
        public static Context getContext() {
            return context;
        }
        ...
    }
    

    After that you can re-use it everywhere in all over your project, like this :

    App.getContext().getString(id)
    

    Please let me know if this does not work for you.

提交回复
热议问题