Android的ScrollView中添加自定义View

本文讨论了在ScrollView中添加自定义View时遇到的问题,重点解释了自定义View高度不确定导致不显示的原因,并提供了在onMeasure方法中设置固定大小的解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做项目的时候,需要在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方法中设置一个固定的大小。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值