博客
关于我
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/

你可能感兴趣的文章
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>