0

Im trying to create two table layouts through activity.. I already have one table layout but how to set through activity? I know to do it through xml but want to do it programatically..

Please Help

freshMan
  • 55
  • 1
  • 3
  • 11
  • please visit this [enter link description here][1] http://stackoverflow.com/a/7915805/3354313 [1]: http://stackoverflow.com/a/7915805/3354313 – Akhil Nov 20 '14 at 11:04

2 Answers2

1

Check this answer and another example here

Just like in xml, you will create a TableLayout, provide params and add rows with your own UI in it.

Community
  • 1
  • 1
Darpan
  • 5,623
  • 3
  • 48
  • 80
1

Take one linear layout(or relative layout) in in your xml get it reference by findViewById() in onCreate() method of your activity.after that create table dynamically and add it to the linear layout.I create a method to do so . ex-

    LinearLayout linear= (LinearLayout ) findViewById(R.id.linear);
    //call method to add the tablelayout.
    linear.addView(createtable(3,5));


 private TableLayout createtable(int requiredcolumn, int requiredrow) {
    TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(
            TableLayout.LayoutParams.MATCH_PARENT,
            TableLayout.LayoutParams.WRAP_CONTENT, 1f);

    TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
    //for border 
    rowParams.setMargins(2, 2, 2, 2);
    TableRow.LayoutParams itemParams = new TableRow.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);

    TableLayout tableLayout = new TableLayout(MainActivity.this);
    tableLayout.setLayoutParams(tableParams);
    tableLayout.setBackgroundColor(Color.WHITE);

    for (int row = 0; row < requiredrow; row++) {
        TableRow tableRow = new TableRow(MainActivity.this);
        tableRow.setLayoutParams(rowParams);

        for (int column = 0; column < requiredcolumn; column++) {
            Random color = new Random();
            int randomColor = Color.argb(255, color.nextInt(256),
                    color.nextInt(256), color.nextInt(256));

            TextView textView = new TextView(MainActivity.this);
            textView.setLayoutParams(itemParams);
            textView.setBackgroundColor(randomColor);

            tableRow.addView(textView);
        }

        tableLayout.addView(tableRow);
    }

    return tableLayout;
}
Chandra Sharma
  • 1,339
  • 1
  • 12
  • 26