Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Invalid cast on ViewTreeObserver.AddOnGlobalLayoutListener


I'm trying to attach a GlobalLayoutListener to a view's OnFinishInflate event. I have created my own class that implements ViewTreeObserver.IOnGlobalLayoutListener, but when I try to add that newly created listener to the ViewTreeObserver, it throws an invalid cast exception? How can it not be able to cast an object that is implementing the only interface that the method parameter accepts?! It makes no sense to me.

// from my view, which only inherits from LinearLayout
protected override void OnFinishInflate()

        _dayNamesHeader = (LinearLayout)FindViewById(Resource.Id.cal_day_names);

        _listViewWeeks = (WeekListView)FindViewById(Resource.Id.list_week);
        _listViewWeeks.SetLayoutManager(new LinearLayoutManager(Context));
        _listViewWeeks.HasFixedSize = true;

        var calViewListener = new CalendarViewOnGlobalLayoutListener(Width, Height, this);


// CalendarViewOnGlobalLayoutListener.cs
public class CalendarViewOnGlobalLayoutListener : ViewTreeObserver.IOnGlobalLayoutListener
    private readonly int _width;
    private readonly int _height;
    private readonly CalendarView _view;

    public CalendarViewOnGlobalLayoutListener(int width, int height, CalendarView calendarView)
        _width = width;
        _height = height;
        _view = calendarView;

    public void OnGlobalLayout()
        if (_width != 0 && _height != 0)

    public void Dispose()

    public IntPtr Handle { get; }

    private void CollapseCalendarView(CalendarView view)
        var layoutParams = (ViewGroup.MarginLayoutParams)view.LayoutParameters;

        layoutParams.Height =
            (Resources.System.GetDimension(Resource.Dimension.calendar_header_height) +
             2 * Resources.System.GetDimension(Resource.Dimension.day_cell_height));

        view.LayoutParameters = layoutParams;

Any ideas why this is happening?

Sign In or Register to comment.