How to get application object into fragment class

大城市里の小女人 提交于 2019-11-29 10:35:54

问题


I am changing my android mobile app to support both tablets and mobile phone. For this I am changing my activity class into fragment. In my activity class I have an instance of my application class created as below:

appCtx = (UnityMobileApp) getApplication();

Where UnityMobileApp is my Application class.

Now I want to create the same instance in my fragment class. Can you guys please help me solve this?


回答1:


Use appCtx = (UnityMobileApp) getActivity().getApplication(); in your fragment.




回答2:


The method getActivity() may have possibility to return null. This may crash your app.So it is safe to use that method inside the onActivityCreated(). Eg:

private UnityMobileApp appCtx;
.
.
...
@Override
public View onCreateView(...){
...
}

@Override public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     appCtx = ((UnityMobileApp) getActivity().getApplication()); 
} 
...
//access the application class methods using the object appCtx....

This answer is derived from Dzianis Yafima's answer asked by Ognyan in comments. Thus the Credit goes to Dzianis Yafima's and Ognyan in stackoverflow.




回答3:


As you are trying yo use application context from fragment you can not use getApplication() because that isn't method of Fragment class
So you first have to use the getActivity() which will return a Fragment Activity to which the fragment is currently associated with.

to sumup in your code,

instead of this.getApplication() you have to use getActivity.getApplication()

know more about getActivity() from android documentation




回答4:


Alternatively using Kotlin

fun bar() {
   (activity?.application as UnityMobileApp).let {
      it.drink()
   } ?: run {
      Log.d("DEBUG", "(╯°□°)╯︵ ┻━┻")
   }
}


来源:https://stackoverflow.com/questions/11585702/how-to-get-application-object-into-fragment-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!