【Android】getwidth和getmeasuredwidth的区别以及两者的使用场景

本文详细解释了Android中View的getWidth()和getMeasuredWidth()的区别及应用场景。getWidth()用于获取已布局View的宽度;getMeasuredWidth()则用于获取View的内容占据宽度,适用于自定义View的onLayout或动态加载View后。

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

首先,看getWidth()的官方说明:

public final int getWidth ()
Added in API level 1

Return the width of the your view.

Returns
  • The width of your view, in pixels.

返回view的宽度,说的不详细,再看getWidth源码:

<span style="font-size:18px;">    /**
     * Return the width of the your view.
     *
     * @return The width of your view, in pixels.
     */
    @ViewDebug.ExportedProperty(category = "layout")
    public final int getWidth() {
        return mRight - mLeft;
    }</span>

从源码可以看出,getwidth返回的是右边坐标减轻坐标减去左边坐标,这要在布局之后才能确定它们的坐标,也就是说在布局后才能调用getwidth来获取。所以getWidth()获得的宽度是View在设定好布局后整个View的宽度。


而对于getmeasuredwidth,

public final int getMeasuredWidthAndState ()
Added in  API level 11

Return the full width measurement information for this view as computed by the most recent call to measure(int, int). This result is a bit mask as defined byMEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL. This should be used during measurement and layout calculations only. Use getWidth() to see how wide a view is after layout.

Returns
  • The measured width of this view as a bit mask.
得到的是最近一次调用measure()方法测量后得到的是View的宽度,它应该仅仅用在测量和Layout的计算中。再看源码:

    /**
     * Like {@link #getMeasuredWidthAndState()}, but only returns the
     * raw width component (that is the result is masked by
     * {@link #MEASURED_SIZE_MASK}).
     *
     * @return The raw measured width of this view.
     */
    public final int getMeasuredWidth() {
        return mMeasuredWidth & MEASURED_SIZE_MASK;
    }

return The raw measured width of this view 获得的是原始的测量宽度。所以说getMeasuredWidth()是对View上的内容进行测量后得到的View内容占据的宽度。前提是你必须在父布局的onLayout()方法或者此View的onDraw()方法里调用measure(0,0);(measure中的参数的值你自己可以定义),否则你得到的结果和getWidth()得到的结果是一样的。


两者的使用场合:

getMeasuredWidth:在自定义view重写onLayout时、在我们用layoutinflater动态加载view后想获得view的原始宽度时。

getWidth:一般在view已经布局后呈现出来了,想获取宽度时


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值