Pages must fill the whole ViewPager2 (use match_parent)
I have found out that the problem is in inflating view holder.
I had the same issue and solved it changing
ViewBinding.inflate(inflater)
to
ViewBinding.inflate(inflater, parent, false)
While struggling with this problem, I figured it out what's the problem was. My use case was I was using androidx.viewpager2.widget.ViewPager2, and calling normal Views in RecyclerView.
If you notice the error carefully you would see something like this:
java.lang.IllegalStateException: Pages must fill the whole ViewPager2 (use match_parent) at androidx.viewpager2.widget.ViewPager2$2.onChildViewAttachedToWindow(ViewPager2.java:170)
Second line is the key to main issue. If you open ViewPager2.java you would see
private RecyclerView.OnChildAttachStateChangeListener enforceChildFillListener() { return new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(@NonNull View view) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams(); if (layoutParams.width != LayoutParams.MATCH_PARENT || layoutParams.height != LayoutParams.MATCH_PARENT) { throw new IllegalStateException( "Pages must fill the whole ViewPager2 (use match_parent)"); } } @Override public void onChildViewDetachedFromWindow(@NonNull View view) { // nothing } };}
Android is not taking the match_parent assigned in xml to attach views. May be future improvements would be done in next release of ViewPager2.
Anyways, for now to fix it, set layout params as MATCH_PARENT explicity.
view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
This view is the parent view holding View Pager childs.
In you case it would be androidx.constraintlayout.widget.ConstraintLayout.
view.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));