最近在做项目的时候,需要在scrollview中添加自己定义的view,部分代码如下:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:customerview="http://schemas.android.com/apk/res/com.rising.customivew" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <com.rising.view.RectProgressView android:id="@+id/rect_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" />
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.EXACTLY || widthSpecMode == MeasureSpec.AT_MOST) { mWidth = widthSpecSize; } else { mWidth = 0; } if (heightSpecMode == MeasureSpec.AT_MOST || heightSpecMode == MeasureSpec.UNSPECIFIED) { mHeight = dipToPx(30);//这里我设置为了固定的大小 } else { mHeight = heightSpecSize; } setMeasuredDimension(mWidth, mHeight); }
原因如下:scrollview在初始化的时候自定义View的高度不确定,无法绘制view,所以view就不显示了,解决方法,就是onmeasure方法中设置一个固定的大小。