user2140182
user2140182

Reputation: 19

How to create UI from code?

I tried to add some controls dynamicaly from code, not from .xml. I used code like:

protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            mainLayout = FindViewById<LinearLayout>(Resource.Id.mainLayout);

            Button test = new Button(Window.Context) { Text = "BLABLABLA" };
            test.SetWidth(100);
            test.SetHeight(100);

            LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent, 0.0f);
            _params.SetMargins(10, 10, 0, 0);
            mainLayout.AddView(test, _params);
        }

But button does not appear in my application. What can be wrong?

UPDATE: Now it works! But I don't understand what I did and why it had not run before. But anyway thank you all.

Upvotes: 0

Views: 322

Answers (2)

poitroae
poitroae

Reputation: 21367

You miss the call setContentView(mainLayout); within your onCreate() method.

Note that you have to call this method after generating your layout.

Upvotes: 1

Emil Adz
Emil Adz

Reputation: 41099

First of all to set the LayoutParams you should set it to the Button test and not the layout like this:

test.setLayoutParams(_params);

and then to add it to the mail layout, like this:

mainLayout.AddView(test);

Upvotes: 0

Related Questions