5

I have a custom view inside an activity, which i am launching with an Application context.

When i call the View.getContext() from within my CustomView and try to cast it:

Activity activity = (Acitivity)View.getContext();

It gives an error that cannot cast the Context from Application to Activity.

Has someone faced this problem before ??? please help

Isaiah
  • 432
  • 2
  • 6
revolutionary
  • 3,314
  • 4
  • 36
  • 53
  • If you're passing the application `Context` to your view why do you try to use as an `Activity` `Context`? – user Sep 12 '13 at 14:56
  • check this link. http://stackoverflow.com/questions/9273218/is-it-always-safe-to-cast-context-to-activity-within-view – John R Sep 12 '13 at 14:56

1 Answers1

3

As Romain Guy says in this post, there is no guarantee that the Context used by your View is an Activity. Also, if you are using the Applcation Context you cannot cast it to the Activity Context; they are different. This link gives a great explanation of all the different flavors of Context

Community
  • 1
  • 1
Emmanuel
  • 13,083
  • 4
  • 39
  • 53
  • I know that, but i need to pass in parameters to my Custom View from the activity. e.g. the Activity wants to tell the custom-view to change its background color and the view should do something in it onDraw() – revolutionary Sep 12 '13 at 15:43
  • You may want to try to create an interface in your `Activity` and have the `View` implement it. You can set some boolean member inside the interface implementation and then call `invalidate()`. Inside `onDraw()` check to see if the boolean is true and update the `View`'s background. – Emmanuel Sep 12 '13 at 15:57