I get imageView's width 0. Below is code.
xml file :
<ImageView
android:id="@+id/img"
android:layout_width="200dp"
android:layout_height="200dp" />
Activity :
@Override
protected void onResume() {
super.onResume();
ImageView img = (ImageView) findViewById(R.id.img);
Log.d(TAG, "width : " + img.getWidth());
}
I don't want to use below code as I need to place this code in so many places.
ViewTreeObserver vto = img.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
ImageView img = (ImageView) findViewById(R.id.img);
Log.d(TAG, "width : " + img.getWidth());
return true;
}
});
My workaround : I actually later did not need to add this code in an activity. I added it to a non-activity class and instead of ImageView's width I used Bitmap image's width and now does not have this problem.
Where you calling
getWidth()
andgetHeight()
on ImageView? If you calling fromonCreate()
in activity, it won't work. You need to wait for activity window to attached and then callgetWidth() and getHeight()
on ImageView. You can try callinggetWidth() and getHeight()
fromonWindowFocusChanged()
method of your activity.call on onWindowFocusChanged like this way
well i found many many questions related that are duplicate to this question, and most of the answers were not fit for my case.
I have come up with a solution that may fit for yours as it does for me. Simply, i have created a custom
ImageView
and added a new callbackOnSizeChangedCallback
that is being called whenever the size of the view is changed to non zero values.Here's a code sample of my own:
and you can simply use it as follows:
related questions:
Since you already have a "fixed" width imageView of 200dp why don't you just put it in dimens.xml
and then simply