Kotlin Android - ViewStub must not be null

1.1k Views Asked by At

I'm using a ViewStub to dynamically inflate layout to a bottom sheet. Everything works fine, except that when the ViewStub once inflated can't be used in code.

For example, once I've inflated a layout (using View.VISIBLE, not .inflate() I can't use the View Stub anymore: if I change visibility it gives me an error.

This is my code:

weight_force_button.setOnClickListener {

         mechanical_view.layoutParams = layoutParams
         mechanical_view.layoutResource = R.layout.sheet_weight_force
         mechanical_view.visibility = View.VISIBLE

        dialog.state = BottomSheetBehavior.STATE_EXPANDED

  }

close_button.setOnClickListener {
            dialog.state = BottomSheetBehavior.STATE_COLLAPSED

            mechanical_view.visibility = View.GONE
        }

This is the error after user click on weight_force_button or close_button:

java.lang.IllegalStateException: mechanical_view must not be null

1

There are 1 best solutions below

2
csar On

ViewStub's 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. Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked. The inflated View is added to the ViewStub's parent with the ViewStub's layout parameters.

Once it's inflated it's removed from its parent and replaced by the inflated layout.