Solution 1 :
use this
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.removeOnGlobalLayoutListener(this);
int width = imageView.getWidth();
int height = imageView.getHeight();
}
});
this is better than adding delay, it run when you view drawn and remove listener after so no memorylake.
Solution 2 :
Try to use this thing:
@BindingAdapter("imageName")
public void bind(ImageView imageView, String imageName) {
imageView.post(() -> {
int width = imageView.getWidth();
int height = imageView.getHeight();
});
}
Problem :
I am using Android databinding and a BindingAdapter to bind an ImageView’s bitmap to a bitmap that I load.
@BindingAdapter("imageName")
public void bind(ImageView imageView, String imageName) {
...
int width = imageView.getWidth();
int height = imageView.getHeight();
...
}
Both width
and height
are zero and I understand from my research and the numerous SO posts that I’m probably calling these methods too early and the layout is not drawn yet.
But I can’t really move the code to another method when I want to use the BindingAdapter. Is there another way to get the measurements of the view or to postpone the binding process?
Comments
Comment posted by Kapta
Just add some delay, and then recheck it
Comment posted by Vincent Mimoun-Prat
Have you tried imageView.post( … )?
Comment posted by flauschtrud
Thank you, that feels way better than a delay. Just as an addition: i had to add this listener on the ViewTreeObserver like so
Comment posted by mahdi shahbazi
@JanaFlauschata Yeah, you are right a just forget it and answer edited now, thanks.