TrustNoOne
TrustNoOne

Reputation: 595

Layout Inflater, ViewGroup and removeView()

I am wondering if someone can explain to me why, when inflating a layout, if a ViewGroup is specified that a later removeView() does nothing. That is:

in onCreate:

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

in a later method:

            getHelp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LayoutInflater inflater = GraphicsActivity.this.getLayoutInflater();
                    final View faqView = inflater.inflate(R.layout.graphfaq, vg);


                    final View faqClose = findViewById(R.id.graph_faq_close);
                    faqClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v2) {
                            if (MainActivity.debug) Log.i(TAG,"inside faqClose listener");
                            vg.removeView(faqView);
                        }
                    });
                }
            });

this inflates and displays the faqVIew properly but when the second clickListener is triggered, the view is not removed.

However, doing it this way does remove the view when clicked to close:

                    final View faqView = inflater.inflate(R.layout.graphfaq, null);
                    vg.addView((faqView));

Just trying to get a better understanding of how this all works.

TIA

Upvotes: 1

Views: 1217

Answers (1)

Simas
Simas

Reputation: 44118

From the docs:

public View inflate (int resource, ViewGroup root)

Returns The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

Meaning:

vg.removeView(faqView);

Is interpreted as:

vg.removeView(vg);

Which doesn't exist there, therefore it can't be removed.

Edit:

Let me put my words differently: vg can't be removed from vg because a view doesn't exist in itself.

Comment: if you don't pass a root, your view won't attach to anything but it will be inflated.

Code sometimes explains it better:

// This returns vg // Basically faqView == vg
View faqView = inflater.inflate(R.layout.graphfaq, vg);

// This find the layout you attached
View yourView = faqView.findViewById(R.id.graphfaq_layout);

// This removes the layout
faqView.removeView(yourView);

As it's been said many times Android Docs are cryptic. You need to read it a few times to get what's going on.

Upvotes: 2

Related Questions