Reputation: 19
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
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
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