Jesse Jesse - 5 months ago 67
Android Question

Align dynamically in xamarin

I'm trying to align my controls using Xamarin Android.

I made a foreach loop with a GridView:

var layout = new GridLayout(this);
SetContentView(layout);

foreach(JObject s in theArray)
{
string Text = s.GetValue("Name").ToString();

var sbLabel = new TextView(this);
sbLabel.Text = Text;

var sbButton = new Button(this);
sbButton.Text = "Info";

layout.AddView(sbLabel);
layout.AddView(sbButton);

}


But I want the TextView and Button to be underneath each other.

How it looks now:

enter image description here

How I want it to look:

enter image description here

Can someone help me with aligning this properly? If possible also centered in the form.

Thanks!

Answer

This can be done by wrapping you Label and Button in LinearLayout:

for (int i = 1; i < 4; i++)
{
    var relative = new LinearLayout(this);
    relative.Orientation = Orientation.Vertical;

    var sbLabel = new TextView(this);
    sbLabel.Gravity = Android.Views.GravityFlags.CenterHorizontal;

    var sbButton = new Button(this);

    sbLabel.Text = i.ToString(); ;

    sbButton.Text = "Info";

    relative.AddView(sbLabel);
    relative.AddView(sbButton);
    layout.AddView(relative);
}

In alternative you can do this with a RelativeLayout (More performant) too (it's a bit more code and you must have and Id for the Label):

for (int i = 1; i < 4; i++)
{
    var relative = new RelativeLayout(this);
    var params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);

    var sbLabel = new TextView(this);
    var layoutparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
    layoutparams.AddRule(LayoutRules.CenterHorizontal);
    sbLabel.LayoutParameters = layoutparams;
    var sbButton = new Button(this);

    sbLabel.Id = i;
    sbLabel.Text = i.ToString();

    sbButton.Text = "Info";

    params1.AddRule(LayoutRules.Below, sbLabel.Id);
    relative.AddView(sbLabel);
    relative.AddView(sbButton, params1);

    layout.AddView(relative);
}

Final result (Same for both options above):

enter image description here