I have a question that seems simple but I cannot figure out what is the best practice for that 🙂
What is the best practice to access from a View, a method on the Activity that launched the View?
For example, I have an Activity with a layout that contains a Button and a Textfield. I want when I click on the Button, to call a method on my Activity that update the Textfield with some value. I come with multiple solutions:
1 – Inner class for the OnClickListener directly on the Activity so I can the method of the Activity with MyActivity.this.updateTextField() on onClick method
2 – Outer class for the OnClickListener, on my onClick method I can do: ((MyActivity)getContext()).updateTextField()
3 – Reference the Activity on my OnClickListener class when I instantiate it:
myButton.setOnClickListener(new MyOnclickListener(MyActivity));
I don´t want solution 1 because I don´t like that much inner class and I want reusable code. Solution 2 seems good but can produce error on runtime if my context is not an activity. Solution 3 seems good also but “heavy”.
What is the best practice on Android to tell from the View to its Actitity that something needs to be done on the Activity?
Thanks!
Although I mostly find myself end up with inner classes, there are other options.
You can create an interface like the following and let your activity implement it:
Now let the Activities that you want implement this interface.
Now, create a class that implements
View.OnclickListenerand set the constructor to get UpdateableTextField as a parameter:And last, in the Activity: