Xamarin.Android, How to unsubscribe from View Tree Observer in

307 views Asked by At

I have a view tree observer like this:

rowsContainerVto = rowsContainerView.ViewTreeObserver;
rowsContainerVto.GlobalLayout += RowsContainerVto_GlobalLayout;

void RowsContainerVto_GlobalLayout (object sender, EventArgs e)
{
    if(rowsContainerVto.IsAlive)
        rowsContainerVto.GlobalLayout -= RowsContainerVto_GlobalLayout;

    vW = rowsContainerView.Width;
    Console.WriteLine ("\r now width is " + vW);
}

What it is supposed to do is to find the width after the view is laid out, which it does perfectly. I just can't figure out how to stop this from running over and over again.

Above is basically based on the suggestion made. This only makes the app crash. When i get rid of the "IsAlive", the loop continue forever. I just can't seem to find a way to stop it after the first time it was drawn and laid out.

1

There are 1 answers

0
Cheesebaron On

Since your EventHandler is anonymous you cannot unsubscribe it again since you do not hold a reference to it.

If you want to stay in the same scope you could do something as follows:

EventHandler onGlobalLayout = null;
onGlobalLayout = (sender, args) =>
{
    rowsContainerVto.GlobalLayout -= onGlobalLayout;
    realWidth = rowsContainerView.Width;
}
rowsContainerVto.GlobalLayout += onGlobalLayout;

Alternatively you could have the EventHandler as a method:

private void OnGlobalLayout(sender s, EventArgs e)
{
    rowsContainerVto.GlobalLayout -= OnGlobalLayout;
    realWidth = rowsContainerView.Width;
}

rowsContainerVto.GlobalLayout -= OnGlobalLayout;

This just means that rowsContainerVto and realWidth must be class member variables.