Android - How to ViewPager with multiple childs wi

2019-05-30 14:24发布

问题:

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
}