How to get maxWidth and maxHeight ImageView parameters?

I have an ImageView declared in xml:

... <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxHeight="60dip" android:maxWidth="60dip" android:scaleType="centerCrop" /> ... 

And I want to programmatically get the values ​​of maxWidth and maxHeight :

 ... ImageView imageView = (ImageView) findViewById(R.id.image); int maxWidth = ? int maxHeight = ? ... 

How can i do this?

+4
source share
2 answers

The corresponding ImageView member variables are mMaxWidth and mMaxHeight , both declared private. Available getter methods are also not available that leave you with one of the options:
Use reflection to check the fields.

Here is an example of how to do this:

 int maxWidth = -1; int maxHeight = -1; ImageView iv = (ImageView) findViewById(R.id.imageview); try { Field maxWidthField = ImageView.class.getDeclaredField("mMaxWidth"); Field maxHeightField = ImageView.class.getDeclaredField("mMaxHeight"); maxWidthField.setAccessible(true); maxHeightField.setAccessible(true); maxWidth = (Integer) maxWidthField.get(iv); maxHeight = (Integer) maxHeightField.get(iv); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } 

Other answers mention getWidth() and getHeight() , but this is not the same. If after checking you run the following snippet, you will see the differences (given that the size and maximum size are not identical at the moment due to the set values ​​or the size of the original image):

 Log.d("TEST", "width="+iv.getWidth()+" || height="+iv.getHeight()); Log.d("TEST", "maxWidth="+maxWidth+" || maxHeight="+maxHeight); 
+9
source

set the width and height of the perimeter to fill the parent element in xml. then from code

 imageview.getHeight(); 

and

 imageview.getWidht(); 

will give you the maximum available width / height of the image that is currently displayed on the screen.

0
source

Source: https://habr.com/ru/post/1383635/


All Articles