主动测量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);
    }
相关推荐
xiaogai_gai1 小时前
高效管理钉钉收款单数据集成到MySQL的技术方案
android·mysql·钉钉
Htht1112 小时前
【Qt】之【Bug】点击按钮(ui->pushButton)触发非本类设置的槽函数
qt·ui·bug
_extraordinary_2 小时前
MySQL 索引(一)
android·数据库·mysql
gjc5922 小时前
MySQL OCP试题解析(2)
android·数据库·mysql·开闭原则
Watink Cpper3 小时前
[Linux]多线程(二)原生线程库---pthread库的使用
android·linux·运维·原生线程库·pthread库
笨鸭先游8 小时前
前台--Android开发
android
fareast_mzh8 小时前
Lightweight App Alternatives
android
pq113_612 小时前
OrangePi Zero 3学习笔记(Android篇)4 - eudev编译(获取libudev.so)
android·笔记·学习
CodeCraft Studio12 小时前
报表控件stimulsoft教程:使用 JoinType 关系参数创建仪表盘
前端·ui
鸿蒙布道师16 小时前
鸿蒙NEXT开发动画案例3
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei