我也遇到过这个问题,但我的情况是一个
FragmentPagerAdapter
向
ViewPager
提供页面。我的问题是,在任何
Fragment
被创建之前(因此无法正确定位其大小),
ViewPager
的
onMeasure()
被调用。
经过一些尝试和实验,我发现
FragmentPagerAdapter
的
finishUpdate()
方法在
Fragment
被初始化后(从
FragmentPagerAdapter
的
instantiateItem()
中)并且在/期间进行页面滚动。我制作了一个小接口:
public interface AdapterFinishUpdateCallbacks
{
void onFinishUpdate();
}
我将其传递给我的FragmentPagerAdapter
并调用:
@Override
public void finishUpdate(ViewGroup container)
{
super.finishUpdate(container);
if (this.listener != null)
{
this.listener.onFinishUpdate();
}
}
这反过来使我能够在我的CustomViewPager
实现上调用setVariableHeight()
:
public void setVariableHeight()
{
if (!this.isSettingHeight)
{
this.isSettingHeight = true;
int maxChildHeight = 0;
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
for (int i = 0; i < getChildCount(); i++)
{
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED));
maxChildHeight = child.getMeasuredHeight() > maxChildHeight ? child.getMeasuredHeight() : maxChildHeight;
}
int height = maxChildHeight + getPaddingTop() + getPaddingBottom();
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.measure(widthMeasureSpec, heightMeasureSpec);
requestLayout();
this.isSettingHeight = false;
}
}
我不确定这是否是最佳方法,如果您认为它好/坏/邪恶,请留下评论,但在我的实现中似乎效果不错 :)
希望这能帮助到某些人!
编辑:我忘记在调用super.measure()
后添加requestLayout()
(否则它不会重新绘制视图)。
我还忘记了将父级的填充添加到最终高度中。
我还放弃了保留原始的width/height MeasureSpecs,转而根据需要创建一个新的。已相应更新代码。
我还遇到的另一个问题是它在ScrollView
中无法正确调整大小,并发现罪魁祸首是使用MeasureSpec.EXACTLY
来测量子项而不是MeasureSpec.UNSPECIFIED
。已更新以反映此更改。
所有这些更改都已添加到代码中。如果您想要查看旧的(不正确的)版本,则可以查看历史记录。