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

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

问题描述

我已经找到<一href="http://stackoverflow.com/questions/4177731/android-how-to-call-method-from-another-class-without-passing-context">one答案出现说我应该创建一个单独的类,使静态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)。在课堂上我打电话,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.

到现在为止我扔一起黑客和类大赦国际呼吁......b.play(本),只是通过上下文B.然而这是pretty的丑陋,看起来像一个坏的使用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类需要上下文来操作的话,我看不出有什么上课问题的一个规定,它(通过在游戏方法的参数,在一个构造的参数等)。

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天全站免登陆