主动测量View的宽高

熟知UI显示流程的同学可能都知道,View要获取到尺寸,必须经过测量才能拿到,而测量则是UI显示流程的一个环节,所以按照成正常情况想要获取到View的尺寸,就需要至少等到View显示过程中的测量环节结束才能拿到。但是在开发过程中,可能有一些小众场景,为了显示效果,需要在View显示流程触发之前,对未固定尺寸的View根据内容获取其宽高,进而做其他显示上处理,如果有这样需求的同学,那么通过本篇你将学会如何在View显示流程触发之前获取View的宽高。

代码我已经封装为一个函数,可以拿来直接用,很简单,我就不再过多赘述。

Kotlin实现代码:

Kotlin 复制代码
   fun viewMeasure(view:View):Size{
        var widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED)
        var heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED)

        // 测量View
        view.measure(widthMeasureSpec, heightMeasureSpec)

         // 获取测量后的宽和高
        var measuredWidth = view.getMeasuredWidth()
        var measuredHeight = view.getMeasuredHeight()

        // 输出宽和高
        Log.d("TextViewMeasure", "Width: $measuredWidth, Height: $measuredHeight")
        return Size(measuredWidth,measuredHeight)
    }

Java实现代码:

java 复制代码
    public Size viewMeasure(View view){
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);

        // 测量View
        view.measure(widthMeasureSpec, heightMeasureSpec);

        // 获取测量后的宽和高
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();

        // 输出宽和高
        Log.d("TextViewMeasure", "Width: "+measuredWidth+", Height: "+measuredHeight);
        return new Size(measuredWidth,measuredHeight);
    }
相关推荐
whysqwhw20 分钟前
OkHttp平台抽象机制分析
android
hsx6661 小时前
Android 内存泄漏避坑
android
whysqwhw1 小时前
OkHttp之okhttp-bom模块的分析
android
餐桌上的王子1 小时前
Android 构建可管理生命周期的应用(二)
android
幽你一默2 小时前
Android 版本差异速查表(开发者视角)
android
不萌2 小时前
android 项目中的屏幕适配方案
android
UI前端开发工作室2 小时前
UI前端与数字孪生融合新领域拓展:智慧教育的虚拟实验室建设
ui
幽你一默2 小时前
Android开发三分钟读懂mvc,mvp,mvvm,mvi
android
小仙女喂得猪4 小时前
2025 源码应用: Retrofit之动态更换BaseUrl
android·android studio
AmazingMQ5 小时前
Android 13----在framworks层映射一个物理按键
android