LayoutParams update not working

I am trying to calculate the size for this image to be downloaded from the Internet using this line imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image); . The problem is that orgHeight becomes null and you cannot divide by zero. But why is orgHeight 0?

 // Add the imageview and calculate its dimensions //assuming your layout is in a LinearLayout as its root LinearLayout layout = (LinearLayout)findViewById(R.id.layout); ImageView image = (ImageView)findViewById(R.id.photo); ImageLoader imgLoader = new ImageLoader(getApplicationContext()); imgLoader.DisplayImage(url, R.drawable.thumbnail_background, image); int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2; int orgWidth = image.getWidth(); int orgHeight = image.getHeight(); //double check my math, this should be right, though int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight); //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( newWidth, newHeight); image.setLayoutParams(params); image.setScaleType(ImageView.ScaleType.CENTER_CROP); layout.updateViewLayout(image, params); 

My xml image looks like this:

 <ImageView android:id="@+id/photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> 
+4
source share
2 answers

Views do not yet lie in the onCreate() method, so their sizes are 0. Send a Runnable from onCreate() to get the correct values:

 image.post(new Runnable() { @Override public void run() { int newHeight = getWindowManager().getDefaultDisplay().getHeight() / 2; int orgWidth = image.getWidth(); int orgHeight = image.getHeight(); //double check my math, this should be right, though int newWidth = (int) Math.floor((orgWidth * newHeight) / orgHeight); //Use RelativeLayout.LayoutParams if your parent is a RelativeLayout LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( newWidth, newHeight); image.setLayoutParams(params); image.setScaleType(ImageView.ScaleType.CENTER_CROP); layout.updateViewLayout(image, params); } }); 
+7
source

You can also use ViewTreeObserver to get values ​​as soon as the layout is done.

Ref - How can you tell when a layout was drawn?

+2
source

All Articles