Henrik
Henrik

Reputation: 1995

How to remove View from Activity RootView

I'm trying to remove an inflated view. This is how I inflate the view:

ViewGroup vg = (ViewGroup)findViewById(android.R.id.content).getRootView();
mOverflowMenuView = View.inflate(this, R.layout.overflow_menu, vg);     

And this is how I try to remove it from onBackPressed

ViewGroup vg = (ViewGroup)(mOverflowMenuView.getParent());
vg.removeView(mOverflowMenuView);

But I get a class cast exception:

03-11 22:47:31.848: E/AndroidRuntime(26357): java.lang.ClassCastException: android.view.ViewRootImpl cannot be cast to android.view.ViewGroup

Any ideas?

Upvotes: 1

Views: 5676

Answers (2)

Henrik
Henrik

Reputation: 1995

Finally solved it. It seems like my View were added to a RelativeLayout under the root. To get that RelativeLayout handle I had to do:

ViewGroup vg = (ViewGroup)findViewById(R.id.board_root_view).getRootView();     
RelativeLayout v = (RelativeLayout)mOverflowListView.getParent();
vg.removeView(v);       

Upvotes: 0

user_CC
user_CC

Reputation: 4776

If you are getting the classcastexception on the below line:

  ViewGroup vg = (ViewGroup)findViewById(android.R.id.content).getRootView();

Then I would suggest that you place an id in the root view of your layout and then inflate it using the findViewById() directly and then use the removeView method.

Upvotes: 2

Related Questions