javaandroidviewstub

How to create an android ViewStub programmatically?


I want to add a ViewStub to my layout. This is how the ViewStub should look like, as xml:

<ViewStub
    android:id="@+id/viewstub_id"
    android:layout="@layout/use_this_layout"
    android:inflatedId="@+id/inflated_stub"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

I have come up with this code, but the layout is not showing.
I'm reusing the id, because I'm deleting and adding the stub again. I guess the code not working has something to do with the constraints or the layout width/height, but I'm not sure. What am I doing wrong?

ViewStub vs = new ViewStub(this);
vs.setId(R.id.viewstub_id);
vs.setLayoutResource(R.layout.use_this_layout);
vs.setInflatedId(R.id.inflated_stub);

ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(0, 0);
vs.setLayoutParams(layoutParams);

ConstraintLayout cl = findViewById(R.id.viewStubWrapper);
ConstraintSet cs = new ConstraintSet();
cs.clone(cl);
cs.connect(ConstraintSet.PARENT_ID, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
cs.applyTo(cl);

cl.addView(vs); // the ConstraintLayout is the ViewStub's parent
vs.inflate();

Solution

  • I found something that seems to work:

      ViewStub vs = new ViewStub(this);
      vs.setId(R.id.viewstub_id);
      vs.setLayoutResource(R.layout.use_this_layout);
      vs.setInflatedId(R.id.inflated_stub);
    
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
      vs.setLayoutParams(lp);
    
      ConstraintLayout cl = findViewById(R.id.viewStubWrapper);
      cl.addView(vs);
      vs.inflate();
    

    Seems like I didn't need the constraints after all, I just needed to use LayoutParams.MATCH_PARENT for width and height instead of 0.