Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
@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?

like image 696
anguish Avatar asked Jan 04 '13 14:01

anguish


1 Answers

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
    };

You can get an instance of the ViewTreeObserver like this:

var contentView = activity.Window.DecorView.FindViewById(Android.Resource.Id.Content);
contentView.ViewTreeObserver.GlobalLayout += ViewTreeObserverOnGlobalLayout;
like image 165
Greg Shackles Avatar answered Oct 18 '22 19:10

Greg Shackles