layout-listener

Listening to the Layout on Xamarin Android PageRenderer! (LayoutListener)

So when you create a Custom Renderer for your Xamarin Forms ContentPage, on Android, sometimes you have to tap into the Android Layout changes on your current page.

For instances like, Orientation changes, Keyboard visibility changes on Android and so on.

This is done by Adding a Layout Listener to our Layout’s ViewTree. 🙂 Confusing? Let’s get to work!

Create a Layout Listener…

First let’s create our Layout Listener, the guy who get’s the call back when the Layout Changes on the ViewTree of our Layout.

public class CustomLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
{
	public void OnGlobalLayout()
	{
		// do whatever the stuff you wanna do here
	}
}

 

We derive to from the IOnGlobalLayoutListener interface, where as you need to implement its OnGlobalLayout() method which get’s the call back when a Layout change occurs.

Add the Listener to the ViewTree…

Next add it to the ViewTreeObserver of your Layout.

[assembly: ExportRenderer(typeof(CustomContentPage), typeof(CustomContentPageRenderer))]
namespace WhateverYourNamespace
{
    public class CustomContentPageRenderer : PageRenderer
    {
        protected override async void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
			var rootView = CrossCurrentActivity.Current.Activity.Window.DecorView.RootView;
			rootView.ViewTreeObserver.AddOnGlobalLayoutListener(new CustomLayoutListener());
		}
	}
}

 

Since I implemented this on a Xamarin Forms Custom Renderer, first I have gained access to the current Activity’s RootView (from a 3rd party library CurrentActivityPlugin) and then I have added my listener to the ViewTreeObserver of my root view. 😀

TADAA! 😀

but you could also…

Oh well good things comes to those who wait.. lol Xamarin Android provides you an event called GlobalLayout where you could also directly subscribe to Layout changes without having to implement your own listener.

rootView.ViewTreeObserver.GlobalLayout += (sender, args) =>
{
	// do whatever the stuff you wanna do here
}

 

Oh well it depends on your implementation requirement though.

Anyways there you have it! 😀

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s