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

And which way is better?

Let me know if the question needs clarification.

+4
source share
3 answers

I decided to answer my question, and not because any of the answers is bad, but because, although they are equally good, none of them gives a complete answer.

It seems that one of the main factors to consider is reuse:

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

By passing the context in the constructor and referring to it as a private variable, you can reuse the class where you want, without changes.

Another factor that will affect your choice is whether your inner class is public or private. It makes no sense to make the inner class public, and then reference the context using MyActivity.this. The application will be forced to close at the moment when you use the class from another action. I would say, however, that the public class belongs to its own file, but it depends on the particular developer.

Finally, the point is simplicity, since it is easier 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 that you need to use the class somewhere else.

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

+3
source

To reuse a transfer, the context is simpler because you can simply copy it to another project. Otherwise, you will have to change all MyActivity.this to OtherProjectActivity.this.

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

+3
source

This is more of a design problem, since having a link in any case will have the same result. Consider the complexity, access level, and other design elements associated with the inner class.

+1
source

All Articles