ashif-ismail
ashif-ismail

Reputation: 1076

How to programmatically create textviews and show as grid

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.

Upvotes: 0

Views: 47

Answers (1)

Napster
Napster

Reputation: 1383

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

Upvotes: 1

Related Questions