Search code examples
androidandroid-tablelayout

Set number of columns in a tablerow dynamically in android


I have a table-layout and i want to add rows to table dynamically. Number of columns in table will also be decided at runtime and I want to put text-views in each cell on some specified cell. Like if i have three rows and each row will have 15 columns and i want to put a text-view in each column at some index that will be decided at runtime. How can i do that. When i try like this

table_row.addView(textview, index, params);

It gives me indexout of bound exception. How can I do that. Any kind of help will be appreciated ,

Many thanks in advance.


Solution

  • You will have to use loop for each row and then add the textview to the row.

    One simple way to do this is

      TableLayout tbl = (TableLayout) findViewById(R.id.table);
      TableLayout.LayoutParams tblparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    
        for(int i=0; i<row_count;i++)
        {
            TableRow row = (TableRow) findViewById(R.id.tableRow2);
    
            TextView tv1 = new TextView(Main.this);
            TextView tv2 = new TextView(Main.this);
            //you will have to do this for all 15 columns   
    
            tv1.setLayoutParams(tblparams);
            tv1.setText("Col1data");
            tv2.setLayoutParams(tblparams);
            tv2.setText("Col2data");
    
    
            row.addView(tv1);
            row.addView(tv2);
    
        }
    

    I havent tried this but hope it works.