Android 如何将应用程序对象放入片段类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11585702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:09:39  来源:igfitidea点击:

How to get application object into fragment class

androidandroid-fragmentsandroid-fragmentactivity

提问by Rakesh Gourineni

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:

我正在更改我的 android 移动应用程序以支持平板电脑和手机。为此,我将我的活动类更改为片段。在我的活动类中,我创建了一个应用程序类的实例,如下所示:

appCtx = (UnityMobileApp) getApplication();

Where UnityMobileAppis my Application class.

UnityMobileApp我的应用程序类在哪里。

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

现在我想在我的片段类中创建相同的实例。大家能帮我解决这个问题吗?

回答by biegleux

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

appCtx = (UnityMobileApp) getActivity().getApplication();在您的片段中使用。

回答by BharathRao

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:

该方法getActivity()可能有可能返回 null。这可能会使您的应用程序崩溃。因此在onActivityCreated(). 例如:

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'sand Ognyanin stackoverflow.

该答案源自 Ognyan 在评论中提出的 Dzianis Yafima 的回答。因此,归功于stackoverflow 中的Dzianis YafimaOgnyan

回答by Alex Nolasco

Alternatively using Kotlin

或者使用 Kotlin

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

回答by Irony Stack

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.

当您尝试使用片段中的应用程序上下文时,您无法使用,getApplication()因为这不是 Fragment 类的方法
所以您首先必须使用getActivity()将返回片段当前关联的片段活动。

to sumup in your code,

总结一下你的代码,

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

而不是this.getApplication()你必须使用getActivity.getApplication()

know more about getActivity()from android documentation

getActivity()android 文档中了解更多信息