Reputation: 3637
I have this XML code:
<LinearLayout
android:id="@+id/linearLayoutInner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@layout/gallery_image_background"
/>
Then this code:
LinearLayout linearLayoutInner = (LinearLayout) findViewById(R.id.linearLayoutInner);
ImageView imageView = new ImageView(thisActivityContext);
imageView.setImageResource(R.drawable.example);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(lp);
linearLayoutInner.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
linearLayoutInner.addView(imageView);
I then call an own function that is meant to scale the bitmap image until one of the sides reach the edge (i.e. so if the original bitmat is twice as wide as tall, it will keep the proportion inside the imageview, something that is apparently not supported by any scaletype setting):
SharedCode.sharedUtilScaleImage(imageView);
And here comes the problem. That function needs to know the size of the view containing the bitmap drawable. if imageView behaves correctly, it should use MATCH_PARENT and hence give the width/height of the linearLayoutInner. However, the following code returns zero:
int heightParent = max(imageView.getLayoutParams().height, imageView.getHeight());
int widthParent = max(imageView.getLayoutParams().width, imageView.getWidth());
How do I solve this? And why am I returned 0 instead of the correct height/width?
Upvotes: 0
Views: 636
Reputation: 3999
Seem like you might be calling from onCreate()
. u need to wait for activity window to attached and then call getWidth()
andgetHeight()
on imageView
.You can try calling getWidth()
and getHeight()
from onWindowFocusChanged()
method of your activity.
Edit
@Override
public void onWindowFocusChanged(boolean hasFocus){
int width=imageView.getWidth();
int height=imageView.getHeight();
}
Upvotes: 1
Reputation: 4752
final ImageView imageView = (ImageView )findViewById(R.id.image_test);
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
imageView .getViewTreeObserver().removeGlobalOnLayoutListener(this);
imageView.getHeight(); // This will return actual height.
imageView.getWidth(); // This will return actual width.
}
});
Upvotes: 3
Reputation: 82563
You're probably calling the code too early, before the View's onMeasure() has been called. Until that happens, its size is unknown.
final ImageView iv....
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//Measure
iv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
Upvotes: 3