主动测量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);
    }
相关推荐
周杰伦的稻香17 小时前
MySQL中常见的慢查询与优化
android·数据库·mysql
他们叫我技术总监17 小时前
Python 列表、集合、字典核心区别
android·java·python
2401_8823515221 小时前
Flutter for OpenHarmony 商城App实战 - 地址编辑实现
android·java·flutter
42nf1 天前
Android 根据platform.pk8和platform.x509.pem生成.jks文件
android·.pk8和.pem生成.jks
摘星编程1 天前
React Native for OpenHarmony 实战:DisplayInfo 显示信息详解
android·react native·react.js
_李小白1 天前
【Android 美颜相机】第六天:GPUImageView解析
android·数码相机
Mr_sun.1 天前
Day04——权限认证-基础
android·服务器·数据库
北辰当尹1 天前
第27天 安全开发-PHP应用&TP框架&路由访问&对象操作&内置过滤绕过&核心漏洞
android·安全·php
yueqc11 天前
Android 线程梳理
android·线程
航Hang*1 天前
Photoshop 图形与图像处理技术——第9章:实践训练2——变换花朵颜色与绘制正方体
图像处理·笔记·学习·ui·photoshop·期末·复习