如何在 BindingAdapter 中访问视图的宽度和高度?

How to access a view's width and height in BindingAdapter?

我正在使用 Android 数据绑定和 BindingAdapter 将 ImageView 的位图绑定到我加载的位图。

@BindingAdapter("imageName")
public void bind(ImageView imageView, String imageName) {
   ...
   int width = imageView.getWidth();
   int height = imageView.getHeight();
   ...
}

widthheight 均为零,我从我的研究和众多 SO 帖子中了解到我可能过早地调用了这些方法并且布局尚未绘制。

但是当我想使用 BindingAdapter 时,我无法真正将代码移动到另一个方法。是否有其他方法来获取视图的测量值或推迟绑定过程?

使用这个

view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
            view.removeOnGlobalLayoutListener(this);
            int width = imageView.getWidth();
            int height = imageView.getHeight();
        }
});

这比添加延迟要好,它 运行 当您查看绘制并在没有 memorylake 之后删除侦听器时。

尝试使用这个东西:

@BindingAdapter("imageName")
public void bind(ImageView imageView, String imageName) {
    imageView.post(() -> {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
    });
}