Duyen Hang Kim
Duyen Hang Kim

Reputation: 183

Bridgecontext can not be cast to Application

I create customview, then get Application from context. But it show error: java.lang.ClassCastException:com.android.layoutlib.bridge.android.BridgeContext cannot be cast to com.ibsv.cheerupkpi.utilities.CheerupKPIApplication

This is my code:

public  CheerupKPIApplication mApplication;

public MenuBottomBar(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

LayoutInflater.from(context).inflate(R.layout.menu_bottom_bar, this);

mApplication = (CheerupKPIApplication) context.getApplicationContext();

}

Please help me!

Upvotes: 1

Views: 1226

Answers (1)

Karakuri
Karakuri

Reputation: 38605

The layout editor in Android Studio only mimics the layout inflation using a sort of mock Context. It doesn't actually have a real Context like you would on a real device, and certainly doesn't have an Application Context since there is no Application running (you aren't even in the runtime of a device).

You can use isInEditMode() in your custom view to avoid running code that doesn't work in the layout editor. In this case you would need to skip the line

mApplication = (CheerupKPIApplication) context.getApplicationContext();

as well as anything that needs to use mApplication to do an initial measure, layout, and draw.

Upvotes: 2

Related Questions