Can anybody explain me this Java code in C#, since I use Mono for Android? For example I can’t find OnGlobalLayoutListener in Mono for Android.
On Android it looks like this:
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int newWidth, newHeight, oldHeight, oldWidth;
//the new width will fit the screen
newWidth = metrics.widthPixels;
//so we can scale proportionally
oldHeight = iv.getDrawable().getIntrinsicHeight();
oldWidth = iv.getDrawable().getIntrinsicWidth();
newHeight = Math.floor((oldHeight * newWidth) / oldWidth);
iv.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
//so this only happens once
iv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
What is the Mono for Android equivalent?
OnGlobalLayoutListeneris an interface, so in C# it is exposed asViewTreeObserver.IOnGlobalLayoutListener. Since C# doesn’t support anonymous classes as seen here in Java, you would need to provide an implementation of that interface and pass that intoAddOnGlobalLayoutListener():You can do this if you want, but the preferred way in Mono for Android is to use events in place of listener interfaces. In this case, it is exposed as the
GlobalLayoutevent:You can get an instance of the ViewTreeObserver like this: