Xamarin Android c# Viewstub only works once and then getting null pointer

349 Views Asked by At

I am trying to use a viewstub to set my view and it works fine the first time however if I call the method again I get a null pointer exception, Any Ideas why this is happening?

here is my code, on the first time around I call this and it works fine.

            ViewStub stub = FindViewById<ViewStub>(Resource.Id.stub);
            stub.LayoutResource = Resource.Layout.overview;
            stub.Inflate();

then when I try to do the same one again with a different layout I get a null pointer exception

            ViewStub stub = FindViewById<ViewStub>(Resource.Id.stub);
            stub.LayoutResource = Resource.Layout.product_view;
            stub.Inflate();
1

There are 1 best solutions below

0
On BEST ANSWER

According to the official documentation:

When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views.

Your ViewStub is replaced by the Resource.Layout.overview after you call stub.Inflate(). You could use FindViewById() to get view in your overview, but can't get the ViewStub any more.