我也遇到了这个问题,但在我的情况下,我有一个FragmentPagerAdapter,它为ViewPager提供它的页面。我遇到的问题是,ViewPager的onMeasure()在任何片段被创建之前被调用(因此不能正确地大小自己)。
经过一些尝试和错误之后,我发现FragmentPagerAdapter的finishUpdate()方法在片段已经初始化(从FragmentPagerAdapter中的instantiateItem())之后被调用,并且在页面滚动之后/期间。我做了一个小界面:
public interface AdapterFinishUpdateCallbacks
{
void onFinishUpdate();
}
我传递到我的FragmentPagerAdapter并调用:
@Override
public void finishUpdate(ViewGroup container)
{
super.finishUpdate(container);
if (this.listener != null)
{
this.listener.onFinishUpdate();
}
}
这反过来允许我调用setVariableHeight()在我的CustomViewPager实现:
public void setVariableHeight()
{
// super.measure() calls finishUpdate() in adapter, so need this to stop infinite loop
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()(否则它不会重绘视图)。
我还忘记在最终高度中添加父元素的填充。
我还放弃了保留原来的宽度/高度度量,以便根据需要创建一个新的度量。已更新相应的代码。
我遇到的另一个问题是,它不会在ScrollView中正确地调整自己的大小,并发现罪魁祸首是用MeasureSpec测量孩子。EXACTLY而不是measurespect . unspecified。更新以反映这一点。
这些更改都已添加到代码中。如果需要,您可以检查历史记录以查看旧的(不正确的)版本。