我已关注this https://stackoverflow.com/questions/9313554/measuring-a-viewpager and that https://stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content答案,我也找到了this http://www.henning.ms/2013/09/09/viewpager-that-simply-dont-measure-up/ link.
我使用这些资源来进行试验和错误。现在我的习惯ViewPager
成功测量其含量,但只显示第一个。仅供参考,我的ViewPager
持有一些复杂的观点,比如ExpendableListView
- 这就是为什么这些资源中的代码都不能完美运行,我需要自己修改代码。
我有 4 个片段(内容),所以我使用pager.setOffscreenPageLimit(3);
这是我的习惯ViewPager
:
public class CustomViewPager extends ViewPager{
public CustomViewPager (Context context) {
super(context);
}
public CustomViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
这是我的CustomPagerTabStrip
:
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
android.view.ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
这是我的 XML:
<RelativeLayout
android:id="@+id/relativePager"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.xxx.yyy.util.CustomViewPager
android:id="@+id/detailPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.xxx.yyy.util.CustomPagerTabStrip
android:id="@+id/detailTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#161C28"
android:textColor="#FFFFFF" />
</com.xxx.yyy.util.CustomViewPager>
</RelativeLayout>
示例案例:
如果第一个片段的高度为 100 像素,则所有其他片段将保持在 100 像素。
因此,如果第二个片段的高度为 130px,它将被剪切为 100px。
当我尝试调试时, the onMeasure
on my CustomViewPager
总是调用 4 次Activity
已创建,但它们都只读取第一个片段。这onMeasure
never之后再次被调用,即使我从一个片段更改(向左/向右滑动)到另一个片段也是如此。
请帮助我,我花了很多时间来让这个东西工作。
如果您需要更多信息,请询问我,感谢您的宝贵时间。