0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arfmann
  • 684
  • 9
  • 30

1 Answers1

2

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.

csar
  • 131
  • 4
  • So, if I put a second ViewStub and then inflate it (I need to inflate more then a single layout because of multiple buttons), the first ViewStub should be avaible again, right? – Arfmann Aug 27 '19 at 23:23
  • I didn't understand quite well, but looking at the code you are trying to hide the inflated layout (the layout that appeared after the View.VISIBLE) right? If that's the case you can get a reference to the inflated layout by setting the attribute `inflatedId` in the `ViewStub` and calling it. https://developer.android.com/reference/android/view/ViewStub – csar Aug 28 '19 at 00:17