如何从非活动类中检索上下文? [英] How to retrieve a context from a non-activity class?

查看:37
本文介绍了如何从非活动类中检索上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个答案 似乎是说我应该创建一个单独的类并创建一个静态 MyApplication 对象并创建一个 get 方法.然后任何类都可以调用 MyApplication.get() 来检索上下文.

I have found one answer that appears to say I should create a separate class and make a static MyApplication object and make a get method. Then any class can call MyApplication.get() to retrieve the context.

还有其他更干净的方法吗?这是我的情况:

Is there any other cleaner way? This is my situation:

我有一个 A 类和一个 B 类.A 类包含一个来自 B 类的对象(我们称之为对象 b).在 A 类中,我称之为b.play()".但是,我得到一个空指针异常,因为类 B 需要将上下文传递给 MediaPlayer.create() 方法.

I have a class A and a class B. Class A contains an object from class B (let's call the object b). In class A I call, "b.play()". However, I get a null pointer exception because class B needs to pass a context to the MediaPlayer.create() method.

直到现在,我拼凑了一个 hack 并从 A 类中调用了...b.play(this)",然后简单地将上下文传递给 B.但是,这非常丑陋,看起来像是对 OOP 的错误使用.

Until now I threw together a hack and from class A I called.... "b.play(this)" and simply passed the context to B. However that is pretty ugly and looks like a bad use of OOP.

有什么想法吗?

推荐答案

如果 B 类需要一个 Context 来操作,那么我认为让 A 类提供给它没有任何问题(通过 play 方法上的参数,构造函数中的参数等).

If class B requires a Context to operate, then I don't see any problem having class A provide that to it (through a parameter on the play method, a parameter in a constructor, etc).

我不认为您通过为 B 类提供完成其工作所需的依赖项来做任何糟糕的 OOP.

I don't think you are doing any poor OOP by providing class B the dependencies that it needs to do it's job.

这篇关于如何从非活动类中检索上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆