0

Create a new TextView programmatically then display it below another TextView

This is what I have tried,but it didn't help.

I need to programmatically create few textview and then display them like this as a grid

In first line : 1st Textview 2nd Textview second line : 3rd Textview 4th Textview

I'm setting the texts from the list.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ashif-ismail
  • 1,037
  • 17
  • 34

1 Answers1

1

Building upon the linked question this is what will work for you

    String[] textArray = {"One", "Two", "Three", "Four","Five","Six"};
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    for( int i = 0; i < textArray.length; i+=2 )
    {
        LinearLayout linearLayout1 = new LinearLayout(this);
        linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
        TextView textView1 = new TextView(this);
        textView1.setText(textArray[i]);
        TextView textView2 = new TextView(this);
        textView2.setText(textArray[i+1]);
        linearLayout1.addView(textView1);
        linearLayout1.addView(textView2);
        linearLayout.addView(linearLayout1);
    }
    <mainLayout>.addView(linearLayout);

Further more you can add LinearLayout.LayoutParams to set the content however you like. And if you'd like to center it then you can use weights

Napster
  • 1,353
  • 1
  • 9
  • 11