ViewPager inside ScrollView not working
Try adding this piece of code before loading your viewPager
NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
scrollView.setFillViewport (true);
Let me know if it helped fix the issue.
The accepted answer resulted in my fragments now being visible. However, it left me with the problem that my NestedScrollView would no longer scroll!
To overcome this, I have created a custom ViewPager (based on this article) that calculates it's height in the required manner.
Here is full code for my CustomViewPager:
package org.example;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
public class CustomViewPager extends ViewPager {
public CustomViewPager(@NonNull Context context) {
super(context);
}
public CustomViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int numChildren = getChildCount();
for (int i = 0; i < numChildren; i++) {
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = Math.max(heightMeasureSpec, MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
}
}
}
catch (Exception e) {
e.printStackTrace();
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
In your layout xml, you'd then just replace android.support.v4.view.ViewPager
with org.example.CustomViewPager
.
(I also removed the new android:fillViewport="true"
attribute from my NestedScrollView element as it seems this is now no longer needed.)
Use android:fillViewport="true"
in ScrollView