开发者

Can anyone explain the difference between passing the activity context to an inner class and just referencing it with MyActivity.this?

开发者 https://www.devze.com 2023-03-20 06:10 出处:网络
And which way is better? Let me k开发者_如何学Gonow if the question needs clarification.For reusing passing the context is easier as you then can simply copy it to another project. Otherwise you have

And which way is better?

Let me k开发者_如何学Gonow if the question needs clarification.


For reusing passing the context is easier as you then can simply copy it to another project. Otherwise you have to change all the MyActivity.this to OtherProjectActivity.this.

But most of all it doesn't matter what you use


I have chosen to answer my own question, not because any of the answers are bad, but because while they are equally good, none provide a complete answer.

It seems that one of the main factors to take into consideration is reusability:

Using MyActivity.this to refer to the context means that you will have to modify your code if you ever decide to use the class in another project/class/context.

Passing the context in the constructor and referencing it as a private variable, allows you to reuse the class wherever you want without modifications.

Another factor that will influence your choice is whether your inner class is public or it is private. It doesn't make sense to make an inner class public and then reference the context with MyActivity.this. The application would force close the moment you use the class from another activity. I would argue though, that a public class belongs in its own file, but that is up to the individual developer.

Lastly there is the matter of simplicity, as it is simpler to write MyActivity.this than to implement a constructor etc. This seeming simplicity can come back and bite you, as you can see above, if you decide you need to use the class somewhere else.

I will continue to use MyActivity.this out of simplicity for all inline eventhandlers, but for any other situation it seems that passing the context to the constructor is best practice.


This is more of a design issue as having a reference either way will have the same result. Consider the complexity, the access level and other design elements related to the inner class.

0

精彩评论

暂无评论...
验证码 换一张
取 消