我在我的项目中使用了一个viewpager,因为viewpager不支持WRAP_CONTENT高度,并且其内容是异步加载的,所以在开始时viewpager的高度为0,因为其中没有内容。其内容为加载,我必须计算内容的高度,并将此值设置为viewpager的高度。 所以,我使用measure()方法,然后调用getMeasuredHeight()来获取高度。当内容不是那么多时,高度是正确的,但如果内容中有很多元素,那么hegiht将不会超过2040px
这是XML:
<RelativeLayout
android:layout_below="@id/line1"
android:id="@+id/status_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:id="@+id/status_pager_title"
android:layout_width="match_parent"
android:layout_height="35dp">
<TextView
android:id="@+id/status_comment_count"
android:drawablePadding="0dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="评论"
/>
<View
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#cccccc"/>
<TextView
android:id="@+id/status_repost_count"
android:drawablePadding="0dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="转发"
/>
</LinearLayout>
<ImageView
android:layout_below="@id/status_pager_title"
android:id="@+id/status_cursor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="matrix"
/>
<android.support.v4.view.ViewPager
android:id="@+id/status_vpager"
android:layout_below="@id/status_cursor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:flipInterval="3000"
android:persistentDrawingCache="animation" />
</RelativeLayout>
我打电话给getMeasured:
LayoutParams layoutParams = viewPager.getLayoutParams();
commentList.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
layoutParams.height = commentList.getMeasuredHeight();
viewPager.setLayoutParams(layoutParams);