anguish anguish - 6 months ago 42
C# Question

OnGlobalLayoutListener in Mono for Android

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() {
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));

//so this only happens once

What is the Mono for Android equivalent?

Answer Source

OnGlobalLayoutListener is an interface, so in C# it is exposed as ViewTreeObserver.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 into AddOnGlobalLayoutListener():

public class MyLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
    public void OnGlobalLayout()
        // do stuff here

vto.AddOnGlobalLayoutListener(new MyLayoutListener());

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 GlobalLayout event:

vto.GlobalLayout += (sender, args) =>
        // do stuff here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download