主动测量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);
    }
相关推荐
用户2070386194923 分钟前
Compose 可点击文本:ClickableText Compose 中的 ClickableSpan
android
常利兵30 分钟前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王43 分钟前
Kotlin-基础语法练习一
android·开发语言·kotlin
闻不多1 小时前
用llamaindex搭建GAR遇到400
android·运维·服务器
阿华的代码王国1 小时前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互
跨界混迹车辆网的Android工程师2 小时前
实现Android图片手势缩放功能的完整自定义View方案,结合了多种手势交互功能
android·交互
wyjcxyyy2 小时前
打靶日记-PHPSerialize
android
传奇开心果编程3 小时前
【传奇开心果系列】Flet框架实现的家庭记账本示例自定义模板
python·学习·ui·前端框架·自动化
安卓开发者13 小时前
Android RxJava 组合操作符实战:优雅处理多数据源
android·rxjava
阿华的代码王国13 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端