Reputation: 458
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?
Upvotes: 5
Views: 3960
Reputation: 10139
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;
Upvotes: 15
Reputation: 17037
Here is an information from Android Developers website :
addOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener)
Register a callback to be invoked when the global layout state or the visibility of views within the view tree changes
Here is the link you can take a look : addOnGlobalLayoutListener. and here onGlobalLayoutListener
Upvotes: 0