How can a custom view get access to its activity?

turtleboy picture turtleboy · Oct 12, 2011 · Viewed 18.2k times · Source

I have a custom view and would like to access a String that is available in its activity. I've seen code that uses getContext() in the view class, but there is no method to access the String that has been made available to its activity via an intent. How to make a String in an activity available to its custom view?

Answer

Tiago Simão picture Tiago Simão · Oct 12, 2011

The getContext() method in the View class returns the context that was passed on its constructor. Usually that's the Activity you want (Activity extends Context). So this probably works for you:

Java:

((Activity)getContext()).someMethod(...);

Kotlin:

(context as? Activity)?.someMethod(...)