我遵循了这个和那个答案,还找到了这个链接。
我使用这些资源进行试错。现在我的自定义
我有4个片段(内容),所以我使用了
这是我的
我使用这些资源进行试错。现在我的自定义
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像素。因此,如果第二个片段的高度为130像素,则会被裁剪为100像素。
当我尝试调试时,我的CustomViewPager
上的onMeasure
在创建Activity
时总是被调用4次,但它们都只读取第一个片段。之后,即使我从一个片段滑动到另一个片段,onMeasure
也永远不会再次被调用。
请帮我解决这个问题,我已经花了很多时间来解决这个问题。如果您需要更多信息,请随时询问,感谢您的时间。