Ariesto
Ariesto

Reputation: 121

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

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 buttons to "MyView.axml".

I'm looking for code like below (except code that actually works):

        string[] textArray = new string[] { "button1", "button2", "button3", "button4" };
        int counter= 3;

        for (int i = 0; i < length; i++)
        {

            var mytest = new button(this);

            mytest.Text = textArray[i];
            mytest.id= textArray[i];

            View(MyView.axml).add(mytest);
        }

The result would be that four buttons are added at the bottom of the view. I can find examples for how to dynamically add controls in Android, but not when using Mono for Android (ie in Visual Studio).

Upvotes: 2

Views: 5326

Answers (1)

Greg Shackles
Greg Shackles

Reputation: 10139

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/Buttons">
</LinearLayout>

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<LinearLayout>(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);
        }
    }
}

Upvotes: 3

Related Questions