博客
关于我
Android 中获取某个控件的宽高
阅读量:385 次
发布时间:2019-03-05

本文共 1475 字,大约阅读时间需要 4 分钟。

Android开发中控件尺寸获取的正确方法

在Android开发过程中,许多开发者在onCreate方法中直接调用getWidth或getMeasuredWidth来获取控件的宽高,这样会导致获取到的值始终为0。这种现象的原因在于,在onCreate方法执行期间,控件尚未被绘制出来,测量(measure)操作尚未完成。因此,直接在onCreate中获取控件尺寸并不是一个可靠的方法。

解决方法

针对上述问题,我们可以采用以下三种方法来正确获取控件的宽高信息:

方法一:手动调用measure方法

这是一种直接且简单的方法,具体实现如下:

int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);imageView.measure(w, h);int height = imageView.getMeasuredHeight();int width = imageView.getMeasuredWidth();

这种方法会触发3次onMeasure()方法,虽然简单,但在实际应用中可能会带来一定的性能开销。

方法二:使用ViewTreeObserver的OnPreDrawListener

这种方法通过在预绘制阶段获取控件尺寸,具体实现如下:

ViewTreeObserver vto = imageView.getViewTreeObserver();vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {    public boolean onPreDraw() {        vto.removeOnPreDrawListener(this);        int height = imageView.getMeasuredHeight();        int width = imageView.getMeasuredWidth();        return true;    }});

这种方法会触发两次onMeasure()方法,相比方法一,性能表现更优。

方法三:使用OnGlobalLayoutListener

这种方法在布局完成后获取控件尺寸,具体实现如下:

ViewTreeObserver vto = imageView.getViewTreeObserver();vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {    @Override    public void onGlobalLayout() {        vto.removeGlobalOnLayoutListener(this);        int height = imageView.getMeasuredHeight();        int width = imageView.getWidth();    }});

这种方法同样会触发两次onMeasure()方法,与方法二性能表现一致。

选择建议

在实际项目中,可以根据具体需求选择合适的方法。我们推荐使用方法三,因为它能够避免重复测量,且在布局完成后获取到的尺寸更为稳定。

转载地址:http://cqnwz.baihongyu.com/

你可能感兴趣的文章
MySQL的InnoDB默认隔离级别为 Repeatable read(可重复读)为啥能解决幻读问题?
查看>>
MySQL的insert-on-duplicate语句详解
查看>>
mysql的logrotate脚本
查看>>
MySQL的my.cnf文件(解决5.7.18下没有my-default.cnf)
查看>>
MySQL的on duplicate key update 的使用
查看>>
MySQL的Replace用法详解
查看>>
mysql的root用户无法建库的问题
查看>>
mysql的sql_mode参数
查看>>
MySQL的sql_mode模式说明及设置
查看>>
mysql的sql执行计划详解
查看>>
mysql的sql语句基本练习
查看>>
Mysql的timestamp(时间戳)详解以及2038问题的解决方案
查看>>
mysql的util类怎么写_自己写的mysql类
查看>>
MySQL的xml中对大于,小于,等于的处理转换
查看>>
mysql的下载安装
查看>>
Mysql的两种存储引擎详细分析及区别(全)
查看>>
mysql的临时表简介
查看>>
MySQL的主从复制云栖社区_mysql 主从复制配置
查看>>
MySQL的事务隔离级别实战
查看>>
mysql的优化策略有哪些
查看>>