Considering at first that you are using ImageView
, one option is to create a variable of type ViewTreeObserver
and use the addOnPreDrawListener
method to stay "watching and listening" to the specific view as it launches in the application, regardless of device resolution. See:
-
getMeasuredHeight()
: Retrieves height of ImageView
-
getMeasuredWidth()
: Retrieves the length of ImageView
See below:
final ImageView iv = (ImageView)findViewById(R.id.iv);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
int height = iv.getMeasuredHeight();
int width = iv.getMeasuredWidth();
return true;
}
});
XML
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
/>
No Kotlin using extensions , this is much simpler. See:
iv.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
iv.viewTreeObserver.removeOnPreDrawListener(this)
val height = iv.measuredHeight
val width = iv.measuredWidth
return true
}
})