如何将ViewPager的高度包裹到当前Fragment的高度?

34

我创建了一个包含ViewPager的ScrollView,但是ViewPager的高度没有增加。当ViewPager内部内容太多时,它会被“挤压”并且表格空间缩小。

我搜索了解决方案并发现问题在于使用了wrap_content,因为ViewPager加载时没有内容。因此, ViewPager保持屏幕高度。我找到的解决方案不适用于FragmentPagerAdapter,因此我编辑了这个问题。

请指引我正确的方向。

问候,Christophe VD.

主要布局如下,底部的时间表是其中一个问题:
enter image description here
需要更像这个:
enter image description here

FragmentPagerAdapter代码:

import android.content.Context;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class film_tabs_adapter extends FragmentPagerAdapter {
    private final String[] TITLES = { "Info", "Comment", "Cast", "Muziek"};
    String[] Film_Data;

    public film_tabs_adapter(FragmentManager fm, String[] Film_Data_in) {
        super(fm);
        Film_Data = Film_Data_in;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }


    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment =null;
        Bundle bundle = new Bundle();
        bundle.putStringArray("Film_Data", Film_Data);
        switch(position) {
            case 0:
                //return new film_info();
                fragment = new film_info();
                fragment.setArguments(bundle);
                return fragment;
            case 1:
                return new film_coment();
            case 2:
                return new film_cast();
            case 3:
                return new film_sound();
            default:
                return new film_info();
        }
    }

}


以及Fragment的类别:

    import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class film_info extends Fragment {
    TextView label_locatie;
    ...
    TableLayout TimeTabel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_film_info, container, false); // layout (activity_film_info) openen
        Context context = inflater.getContext();
        DatabaseVerwerker DB = new DatabaseVerwerker(context);
        String[] Film_Data =  getArguments().getStringArray("Film_Data");
        ...
        return view;
    }

}

活动:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:fillViewport="true"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:id="@+id/header">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="120dp">

                <ProgressBar
                    style="?android:attr/progressBarStyleHorizontal"
                    android:progressDrawable="@drawable/redprogressbar"
                    android:layout_width="match_parent"
                    android:layout_height="2dp"
                    android:id="@+id/DownloadCover"
                    android:layout_gravity="top" />

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/FilmCover"
                    android:src="@drawable/cover"
                    android:adjustViewBounds="true"
                    android:padding="-5dp"
                    android:scaleType="centerCrop" />

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|right|top"
                android:paddingLeft="7dp">

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TableRow
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent">

                        <ImageView
                            android:layout_width="82dp"
                            android:layout_height="120dp"
                            android:id="@+id/FilmPoster"
                            android:src="@drawable/poster_x"
                            android:adjustViewBounds="true"
                            android:layout_gravity="bottom|left" />
                    </TableRow>

                    <TableRow
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="New Text"
                            android:id="@+id/FilmTitel"
                            android:textStyle="bold"
                            android:gravity="center_horizontal"
                            android:layout_marginTop="120dp" />
                    </TableRow>
                </LinearLayout>

            </FrameLayout>

        </FrameLayout>

        <FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/body">
            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:context=".MainActivity" >

                <com.astuetz.PagerSlidingTabStrip
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#dadada"
                    app:pstsShouldExpand="true"
                    app:pstsDividerColor="#EDEDED"
                    app:pstsIndicatorColor="#C3263E"
                    app:pstsDividerPadding="10dp"
                    app:pstsIndicatorHeight="4dp"
                    app:pstsTabPaddingLeftRight="0dp"
                    />

                <android.support.v4.view.ViewPager
                    android:id="@+id/pager"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/tabs"
                    tools:context=".MainActivity"
                    android:soundEffectsEnabled="false" />

            </RelativeLayout>
        </FrameLayout>
    </LinearLayout>
</ScrollView>

片段(Fragment):

<?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="999dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="5dp"
                android:background="#dadada">

                <TableLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:stretchColumns="*">

                    <TableRow
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView3"
                                android:src="@drawable/icon_locatie"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView3"
                                android:layout_alignTop="@+id/imageView3"
                                android:layout_toRightOf="@+id/imageView3"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_locatie" />

                        </RelativeLayout >

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView4"
                                android:src="@drawable/icon_speelduur"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView4"
                                android:layout_alignTop="@+id/imageView4"
                                android:layout_toRightOf="@+id/imageView4"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_speelduur" />
                        </RelativeLayout>

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView5"
                                android:src="@drawable/icon_genre"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView5"
                                android:layout_alignTop="@+id/imageView5"
                                android:layout_toRightOf="@+id/imageView5"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_genre" />
                        </RelativeLayout>
                    </TableRow>

                    <TableRow
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView6"
                                android:src="@drawable/icon_gesproken"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView6"
                                android:layout_alignTop="@+id/imageView6"
                                android:layout_toRightOf="@+id/imageView6"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_gesproken" />
                        </RelativeLayout>

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView7"
                                android:src="@drawable/icon_versie"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView7"
                                android:layout_alignTop="@+id/imageView7"
                                android:layout_toRightOf="@+id/imageView7"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_versie" />
                        </RelativeLayout>

                        <RelativeLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:layout_margin="4dp">

                            <ImageView
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentTop="true"
                                android:layout_width="30dp"
                                android:layout_height="32dp"
                                android:id="@+id/imageView8"
                                android:src="@drawable/icon_ondertiteling"
                                android:layout_margin="2dp" />

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_alignBottom="@+id/imageView8"
                                android:layout_alignTop="@+id/imageView8"
                                android:layout_toRightOf="@+id/imageView8"
                                android:gravity="center_vertical"
                                android:text="Small Text"
                                android:id="@+id/label_ondertiteling" />
                        </RelativeLayout>
                    </TableRow>

                    <TableRow
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"></TableRow>
                </TableLayout>
            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="7dp"
                android:paddingRight="7dp">

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/label_beschrijving"
                    android:layout_marginBottom="16dp"
                    android:textSize="14sp"
                    android:text="@string/film_FilmBeschrijving" />
            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="7dp"
                android:paddingRight="7dp">

                <TableLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/timetabel"
                    android:stretchColumns="*"
                    android:shrinkColumns="*"
                    android:background="@drawable/tb_body" />
            </FrameLayout>
        </LinearLayout>
    </FrameLayout>

你要在你的时间表中插入哪些视图? - tachyonflux
我认为这可能与表格单元格的高度、表格布局或其父视图的高度有关,但为了确保需要查看XML代码。 - Shreyans jain
@shreyansjain已编辑帖子并添加了XML布局代码。 - user3142817
你实际上是在遇到表格布局的问题,对吗?@user3142817 - Swaminathan V
6个回答

69
您可以自定义ViewPager,在页面滑动时调整其大小以适应当前页面的大小。
您可以使用以下代码。
public class WrapContentViewPager extends ViewPager {

    private int mCurrentPagePosition = 0;

    public WrapContentViewPager(Context context) {
        super(context);
    }

    public WrapContentViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
            if (wrapHeight) {
                View child = getChildAt(mCurrentPagePosition);
                if (child != null) {
                child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child.getMeasuredHeight();

                heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void reMeasureCurrentPage(int position) {
        mCurrentPagePosition = position;
        requestLayout();
    }
}

在xml文件中声明:

    <your.package.name.WrapContentViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    </your.package.name.WrapContentViewPager>

在页面滑动后调用reMeasureCurrentpage函数。

final WrapContentViewPager wrapContentViewPager = (WrapContentViewPager) findViewById(R.id.view_pager);

wrapContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        wrapContentViewPager.reMeasureCurrentPage(wrapContentViewPager.getCurrentItem());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

我应该在活动中还是片段中添加your.package.name.WrapContentViewPager呢?我已经添加了XML布局。 - user3142817
1
不要使用 android.support.v4.view.ViewPager,而是使用 WrapContentViewPager。 - Abhishek V
1
列表视图中可能有数百行数据。对于ListView,使用wrap_content并不是一个好主意。你需要为ListView指定固定的高度或者使用match_parent - Abhishek V
1
View child = getChildAt(mCurrentPagePosition); 返回 null。无法找出原因。 - Farid
1
View child = getChildAt(mCurrentPagePosition); 对我来说也返回 null ... 有人能帮忙吗? - Felipe A.
显示剩余4条评论

18

我非常喜欢@abhishek-v的答案,但进行了一些升级:

  • addPageChangeListener(...) 在我们的 ViewPager 中调用(在页面滑动时不需要手动在外部调用 reMeasureCurrentPage(...)
  • 不需要存储 mCurrentPagePosition,因为我们可以使用 getCurrentItem()
  • 删除了无用的 try/catch

现在的ViewPager看起来像这样:

public class WrapContentViewPager extends ViewPager {

    public WrapContentViewPager(Context context) {
        super(context);
        initPageChangeListener();
    }

    public WrapContentViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPageChangeListener();
    }

    private void initPageChangeListener() {
        addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                requestLayout();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        View child = getChildAt(getCurrentItem());
        if (child != null) {
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

1
这个解决方案并不完全正确,因为当视图页到达片段列表的末尾时,getChildAt()返回null,并且视图页高度设置为0。最好有一个字段来保存高度,并在视图为空时使用它。 - Rookie
2
我也遇到了getChildAt()在我的第三个(也是最后一个)片段中返回null的问题。为了解决这个问题,我没有调用viewPager.setOffscreenPageLimit(2),而是简单地将上面代码中的View child = getChildAt(getCurrentItem());替换为**Fragment childFragment = (Fragment)getAdapter().instantiateItem(this, getCurrentItem()); View child = childFragment.getView();**(感谢另一个问题的这个答案:https://dev59.com/D2Qn5IYBdhLWcg3w36Q1#16512217)。 - ban-geoengineering

15

终于找到了一个更好的WrapContentViewPager解决方案!

其他的方案存在一些难以解决的bug,但我认为这个方案可以简单地应用在我们的代码中。

我在这个网站上找到了它:https://github.com/akhahaha/burn-android/blob/master/app/src/main/java/com/ucla/burn/android/WrapContentViewPager.java

这是代码:

public class WrapContentViewPager extends ViewPager {
        public WrapContentViewPager(Context context) {
            super(context);
        }

        public WrapContentViewPager(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);
        }
    }

4

在我的情况下,我使用ViewPager创建了一个ImageSlider。孩子的初始值为null,在索引结束时,孩子的值也为null。因此,我对重复的答案进行了一些升级,因为它无法处理(child==null)

现在的ViewPager看起来像这样:

public class WrapContentViewPager extends ViewPager {

    public WrapContentViewPager(Context context) {
        super(context);
        initPageChangeListener();
    }

    public WrapContentViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPageChangeListener();
    }

    private void initPageChangeListener() {
        addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                requestLayout();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        View child = getChildAt(getCurrentItem());
        if (child != null) {
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
        } else {for(int i = 0; i < getChildCount(); i++) {
                View child2 = getChildAt(i);
                child2.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child2.getMeasuredHeight();
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
        }}
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}

此外,如果viewpager的最后一个项目与circlepageindicator粘在一起,您可以根据需要添加任意高度,如下所示:int h = child2.getMeasuredHeight()+50;

这个会正常工作。但是当我们倒序从最后开始刷卡时,它会减小高度并裁剪布局。 - Bhavin Solanki

2
如果这些答案仍然无法解决问题,我可以提供另一种选择。 在PagerAdapter的java文件中,您可以手动测量page的高度,并在instantiateItem方法中设置容器的LayoutParams.height。像这样:
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
    View view = generateView(mContext, position);
    view.measure(View.MeasureSpec.makeMeasureSpec(DensityUtil.getScreenWidth(mContext), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    container.getLayoutParams().height = view.getMeasuredHeight();
    container.addView(view);
    return view;
}

什么是DensityUtil? - Ahmed Elsayed

1
在Android 8.0上,您需要调用另一个requestLayout才能使其工作:
....@Abhishek's answer

sharePager.post(new Runnable() {
            @Override
            public void run() {
                sharePager.requestLayout();
            }
        });

把这个放在哪里? - John61590
@John61590 在 ViewPager 创建后,我将其放在 addOnPageChangeListener 之后。 - legendmohe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接