Exception When Removing Button from StackLayout on Android

AshleyPringleAshleyPringle ✭✭USMember ✭✭

Hi there,
I have a cross platform iOS/Android Forms project that crashes on Android any time a Button is removed from a StackLayout, or a StackLayout with a Button in it is removed from the page's Content.

The most simple version of the code in Forms that causes the crash looks like this:
`
public class LoginPageTest : ContentPage
{
StackLayout Layout1;
StackLayout Layout2;
Button OnBoardLoginButton;
Label Label1;

public LoginPageTest()
{
    Layout1 = new StackLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };

    OnBoardLoginButton = new Button { Text = "PRESS ME" };
    OnBoardLoginButton.Pressed += OnLoginButtonPressed;
    Layout1.Children.Add(OnBoardLoginButton);

    Content = Layout1;
}

private void OnLoginButtonPressed(object sender, EventArgs e)
{
    Layout1.Children.Remove(OnBoardLoginButton);
}

}
`

The error reported is:
Unable to activate instance of type Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer from native handle 0xbe8b2e6c (key_handle 0x3004107).

The same error happens on Android (but not iOS) if the Content property of the page is changed from one StackLayout with a Button in it to another StackLayout.

This error doesn't happen on iOS. It only happens on Android and happens on devices and the simulator.

Is this normal behaviour? I have some ideas on how to work around it, but I'd like to avoid implementing them and keep the same code if I can, since it already works fine in iOS.

Thanks for your time.

Posts

  • ClintStLaurentClintStLaurent ✭✭✭✭✭ USUniversity ✭✭✭✭✭

    Honestly it doesn't surprise me. When you go against good practices all sorts of unexpected bad things happen. Something is probably about half rendered when yo remove it and suddenly there is no reference etc.

    Try following accepted practices by building your UI in XAML... and don't add/remove controls from code behind like that. This is not Windows Forms circa 1997.

  • AlessandroCaliaroAlessandroCaliaro ✭✭✭✭✭ ITMember ✭✭✭✭✭
    I think you should hide, not remove
  • AshleyPringleAshleyPringle ✭✭ USMember ✭✭

    @AlessandroCaliaro said:
    I think you should hide, not remove

    Thanks Alessandro. This was my planned workaround.

  • AlessandroCaliaroAlessandroCaliaro ✭✭✭✭✭ ITMember ✭✭✭✭✭
    It’s not a workaround, it’s the solution
  • AshleyPringleAshleyPringle ✭✭ USMember ✭✭

    @AlessandroCaliaro said:
    It’s not a workaround, it’s the solution

    Ok. Thanks for the solution.

Sign In or Register to comment.