gpt4 book ai didi

java - Android - 使用不同高度的 child 更新 ViewPager

转载 作者:太空狗 更新时间:2023-10-29 14:58:42 26 4
gpt4 key购买 nike

我有一个没有 fragment (只是 View )的 ViewPager 实现。每个页面都包含一个元素列表,但该列表的大小并不总是相同。

我尝试使用此代码设置 ViewPager 维度(扩展 ViewPager 以便我可以覆盖此函数):

    @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);
}

问题是它为每个页面设置了相同的高度。我需要每个页面的自定义高度,具体取决于列表的高度。

我还尝试在 ViewPager 上使用 setOnPageChangeListener 调用 requestLayout()invalidate(),但大小保持不变。也许我做错了......

下面是一些可能有用的代码:

我的 PagerAdapter 的一部分:

        @Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_home_pager,
container, false);

mContainerView = (ViewGroup) view.findViewById(R.id.news_container);
reloadNews(position);

// Add the newly created View to the ViewPager
container.addView(view);

// Return the View
return view;
}

我的 XML 布局的一部分:

        <ScrollView
android:id="@+id/news_scrollview"
android:layout_width="match_parent"
android:layout_height="fill_parent">

<com.ViewPagerWithHeight
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"/>

</ScrollView>

非常感谢你帮助我,

最佳答案

ViewPager 高度不能像您希望的那样随页面变化。您可以尝试子类化 ViewPager 以添加此功能,但处理不同大小页面之间的视觉转换将非常繁琐。另一种选择可能是在每次页面更改时重新测量 ViewPager(但我希望转换看起来很糟糕)。您需要设置页面更改监听器,然后在 ViewPager 上调用 requestLayout。您的 ViewPager onMeasure 只需要找到当前可见子项的高度,并将 ViewPager 高度设置为与之匹配。

旁白:我没看到你在打电话 setMeasuredDimension任何地方。测量 View 时,必须使用计算出的宽度和高度调用此方法,以通知 View 测量的尺寸。当前,您正在自定义 onMeasure 末尾调用 super.onMeasure,这虽然有效,但意味着 ViewPager 将始终使用“默认”宽度和高度。在这种情况下,它恰好与最大页面的高度相匹配。

请参阅 onMeasure 的文档更多细节。特别是:

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

关于java - Android - 使用不同高度的 child 更新 ViewPager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com