Programmatically/Dynamically Add Button Controls to View using Mono for Android {example}

前端 未结 1 426
星月不相逢
星月不相逢 2021-01-24 18:24

Looking for an example of how to dynamically add controls from the activity.

Inside an activity, lets call it \"Activity2.cs\", dynamically add a variable number of butt

1条回答
  •  感动是毒
    2021-01-24 18:51

    Let's say your layout file looks like this (Main.axml):

    
    
    
    

    Then in your activity you can add Button objects to the layout like this:

    [Activity(Label = "Buttons", MainLauncher = true, Icon = "@drawable/icon")]
    public class ButtonActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
    
            SetContentView(Resource.Layout.Main);
    
            var buttons = FindViewById(Resource.Id.Buttons);
    
            for (int i = 1; i <= 4; i++)
            {
                var button = new Button(this);
                button.Text = "Button " + i;
                button.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,
                                                                     ViewGroup.LayoutParams.WrapContent);
    
                buttons.AddView(button);
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题