I have a fragment in which I placed the ViewPager with TabLayout, the contents of the ViewPager is the fragment containing the ListView.
I know that my ViewPager cannot use wrap_content, the height at the beginning is not calculated.
So, I did this:
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
if (tab == null) {
return;
}
int width = getMeasuredWidth();
if (wrapHeight) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
Fragment fragment = ((Fragment) getAdapter().instantiateItem(this, getCurrentItem()));
heightMeasureSpec = getMeasureExactly(fragment.getView(), widthMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
int getMeasureExactly(View child, int widthMeasureSpec) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = calculateHeight ((ListView)child.findViewById(R.id.list));
System.out.println("Height is: "+height);
return MeasureSpec.makeMeasureSpec(height , MeasureSpec.EXACTLY);
}
private int calculateHeight(ListView list) {
int height = 0;
for (int i = 0; i <10; i++) {
View childView = list.getAdapter().getView(i, null, list);
childView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height+= childView.getMeasuredHeight();
}
return height;
}
I get a list with 10 lines to populate, but only 9 are visible, one of them goes out of view.
The question is how can I accurately measure the height of the list line and add it up to 10 elements.
This question haunts stackoverflow, but there seems to be no concrete solution. In particular, for a child of a ListView. How can I make it work with TableLayout.
I also know how recordings and scrolling do it, but it’s by design, and I can’t do it.
- , 10 ( 10 + )