And which way is better?
Let me know if the question needs clarification.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.