12

When I create a custom View, where in some cases I need to cast the Context class passed via the constructor for the Activity class, for making some tasks like inflate a View directly inside my custom View class, I'm getting the following error:

java.lang.ClassCastException: com.android.layoutlib.bridge.android.BridgeContext cannot be cast to android.app.Activity

This is the line throwing this error:

View headerView = ((Activity) context).getLayoutInflater().inflate(R.layout.fragment_history_list_header, null);

It seems like this error only occurs when Eclipse tries to inflate the view to be showed in the XML editor (not occurs in runtime).

Does someone know how to fix it?

Thanks in advance.

Jorge Gil
  • 4,265
  • 5
  • 38
  • 57

1 Answers1

8

Change the call to the following. The reason you are getting a class cast exception is because BridgeContext is not of type Activity.

View headerView = LayoutInflater.from(context).inflate(R.layout.fragment_history_list_header, null);
Bobbake4
  • 24,509
  • 9
  • 59
  • 94
  • Similar issue for me. `if (((Activity)getContext()).isTaskRoot())` is the line causing my problem, which is not solved by your (also quite helpful) inflater fix. I'll be back if I find a solution... – William T. Mallard Nov 23 '13 at 21:53
  • 4
    Sort of. More of a kobyashi maru thing. I only saw the bridge context problem in the ADT graphical editor in Eclipse, and guessed that the error was from the editor trying to execute the code for the custom view, and not the unable-to-inflate problem I was having when I ran the app (which turned out to by a simple sleepy-headed typo :( ). In order to still use the layout editor, I used `if (!View.isInEditMode()) {}` to surround any context-dependent code. The preview isn't pretty, but it lets me still see the other controls. – William T. Mallard Nov 26 '13 at 05:40
  • Thank you @William T. Mallard. The solution is to surround cast to custom activity with if (!View.isInEditMode()) {}. This was driving me crazy. – Hermandroid Jan 27 '16 at 20:02