Android的ScrollView中添加自定义View

来源:互联网 发布:mac u盘启动盘制作 编辑:程序博客网 时间:2024/05/23 10:46

最近在做项目的时候,需要在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" />
经过多次测试发现,里面自定义的view一直不显示,最后调试找到了原因,原来是在onMeasure方法中的高度一直都是0。
@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方法中设置一个固定的大小。

0 0
原创粉丝点击