Android ViewPager with dynamic height
I found a good solution here If anyone else was wondering how to make ViewPager change It's height dynamically.
Also you can find quick answer here If you don't have time to look at Git.
Hamidreza Salehi
Currently I managing mobile app projects is Pishro Samaneh Arad company. sometimes I do programming myself for both iOS and Android platforms. Some years before I wrote codes in C# and ASP.NET MVC. In 2016 I graduated from Iran University of Science & Technology in software engineering with MA degree. Dr. Saeed Parsa was my teacher and supervisor. I do some works in graphical designing field too.
Updated on June 14, 2022Comments
-
Hamidreza Salehi almost 2 years
I have a
ViewPager
to show some Fragments and swipe between them but the height of theViewPager
is dynamic based on the content. Assume I have multiple list that each list placed in one tab and by changing tabs the height ofViewPager
should change properly I created a customViewPager
and overridedonMeasure
but the problem isViewPager
creates the next fragment sooner that current fragment (visible one) gets It's height from next fragment measure.Here is
MyViewPager
:public class MyViewPager extends ViewPager { public MyViewPager(Context context) { super(context); } public MyViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for(int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure( widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) ); int h = child.getMeasuredHeight(); if(h > height) height = h; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
I also tried to trigger
onMeasure
method ofMyViewPager
when the fragment become visible like below but nothing changes.@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { PostDetailsActivity activity = (PostDetailsActivity) getActivity(); activity.pagerParent.requestLayout(); activity.pagerParent.invalidate(); } }