我已经找到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.
更多推荐
如何检索来自非活动类的上下文?
发布评论