5

In my app I use a Xamarin.Forms AbsoluteLayout. I have a custom menu bar. When I clicked on a menu button, the main content (a View) of my AbsoluteLayout is supposed to be replaced.

So far I can only achieve that by adding a new child and setting its layout bounds using Children.Add() and SetLayBounds(). But this way I'm adding more and more children and never remove them.

What is the proper way to remove a child from an AbsoluteLayout?

kaolick
  • 4,817
  • 5
  • 42
  • 53

2 Answers2

11

.Children implements IList<View> (and ICollection<View>, IEnumerable<View>, Ienumerable) so you can use at your best convenience:

  • layout.Children.RemoveAt (position),
  • layout.Children.Remove (view),
  • layout.Children.Clear ()

provide you know the index of your view in .Children, you can also replace the element in place:

layout.Children[position] = new MyView ();

but that gives you less options than the Children.Add (...) overrides and you'll have to use SetLayoutBounds and SetLayoutFlags.

Stephane Delcroix
  • 16,134
  • 5
  • 57
  • 85
0

Try the following snippet that uses the RemoveAt method of the AbsoluteLayout.Children collection.

Alternatively you can use the Remove(View) method if you have a variable reference.

        StackLayout objStackLayout = new StackLayout()
        {
        };
        //
        AbsoluteLayout objAbsoluteLayout = new AbsoluteLayout()            
        {
        };
        //
        BoxView objBox1 = new BoxView()
        {
            Color = Color.Red,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox1, new Point(100,100));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        BoxView objBox2 = new BoxView()
        {
            Color = Color.Green,
            WidthRequest = 50,
            HeightRequest = 50,
        };
        objAbsoluteLayout.Children.Add(objBox2, new Point(200, 200));
        System.Diagnostics.Debug.WriteLine("Children Count : " + objAbsoluteLayout.Children.Count);
        //
        Button objButton1 = new Button()
        {
            Text = "Remove First Child"
        };
        objButton1.Clicked += ((o2, e2) =>
            {
                if (objAbsoluteLayout.Children.Count > 0)
                {
                    // To Remove a View at a specific index use:-
                    objAbsoluteLayout.Children.RemoveAt(0);
                    //
                    DisplayAlert("Children Count", objAbsoluteLayout.Children.Count.ToString(), "OK");
                }
                else
                {
                    DisplayAlert("Invalid", "There are no more children that can be removed", "OK");
                }
            });

        //
        objStackLayout.Children.Add(objAbsoluteLayout);
        objStackLayout.Children.Add(objButton1);
Pete
  • 4,746
  • 2
  • 15
  • 21