Android - How to ViewPager with multiple childs with different heights

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

I have a ViewPager and in its adapter I have 3 childs(Fragments). These 3 childs should have different heights measured on content.

I have already tried to override the onMeasure Methode in ViewPager like this (src: stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content/18167273#18167273)

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     super.onMeasure(widthMeasureSpec, heightMeasureSpec);     View view = null;      for (int i = 0; i < getChildCount(); i++) {         // find the first child view         view = getChildAt(i);         if (view != null) {             // measure the first child view with the specified measure spec             view.measure(widthMeasureSpec, heightMeasureSpec);         }           setMeasuredDimension(getMeasuredWidth(),          measureHeight(heightMeasureSpec, view));     }  } 

But this don't work for all the childs in the ViewPager it only sets one height for all.

This is the CustomViewPager extended from ViewPager:

This is the adapter for viewPager:

public class MyPagerAdapter extends FragmentPagerAdapter {      private final String[] TITLES = { "card1", "card2", "Card3" };      public MyPagerAdapter(FragmentManager fm) {         super(fm);     }      @Override     public CharSequence getPageTitle(int position) {         return TITLES[position];     }      @Override     public int getCount() {         return TITLES.length;     }      @Override     public Fragment getItem(int position) {         switch (position) {         case 0:             return CookCardFragment.newInstance(position);          case 1:             return RecipeCardFragment.newInstance(position);          case 2:             return CookCardFragment.newInstance(position);         }         return null;     }  } 

回答1:

Do one thing just try to change the height of viewpager control every time you call new fragment in your FragmentActivity



回答2:

@Override     public float getPageWidth(int position) {     return 0.98f; //(0-1] this values specifies how much space a page will occupy on screen } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!