My problem was to create a dynamic table and not hard xml-coded. So I’ve wrote a table class to create it programmatically. The created table has also borders.

TableGenerator class

public class TableGenerator {
    private final Context mContext;
    private TableLayout mTable;

    private TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams();
    private TableRow.LayoutParams colParams = new TableRow.LayoutParams();

    public TableGenerator(Context context) {
        mContext = context;
        mTable = new TableLayout(context);
        rowParams.setMargins(0, 0, 0, 1);
        colParams.setMargins(0, 0, 1, 0);

        TableLayout.LayoutParams lptable = new TableLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mTable.setLayoutParams(lptable);

        mTable.setStretchAllColumns(true);
        mTable.setBackgroundColor(mContext.getResources().getColor(
                R.color.table_background));
    }

    public void addRow(String[] data) {
        TableRow tr = new TableRow(mContext);
        tr.setBackgroundColor(mContext.getResources().getColor(
                R.color.table_background));

        tr.setLayoutParams(rowParams);

        for (int iCol = 0; iCol < data.length; iCol++) {
            TextView tvCol = new TextView(mContext);
            tvCol.setText(data[iCol]);
            tvCol.setGravity(Gravity.CENTER | Gravity.CENTER);
            tvCol.setPadding(3, 3, 3, 3);
            tvCol.setTextColor(mContext.getResources().getColor(
                    R.color.text_black));
            tvCol.setLayoutParams(colParams);
            tvCol.setBackgroundColor(mContext.getResources().getColor(
                R.color.row_background));
            tr.addView(tvCol);
        }

        mTable.addView(tr);
    }

    public TableLayout getTable() {
        return mTable;
    }
}

how to use the class:

MainActivity class

public class MainActivity extends Activity {
	private ScrollView layMain;
	private TableGenerator mTable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);

		showTable();
	}

	private void showTable() {
		mTable = new TableGenerator(getApplicationContext());
		layMain = (ScrollView)findViewById(R.id.table);

		String[] firstRow = {"col1", "col2", "col3", "col4"};
		String[] secondRow = {"11", "12", "13", "14"};
		String[] thridRow = {"2a", "2b", "2c", "2d"};

		mTable.addRow(firstRow);
		mTable.addRow(secondRow);
		mTable.addRow(thridRow);

		layMain.removeAllViews();
		layMain.addView(mTable.getTable());
	}
}

to successfully use the code above you need to set the main.xml in layout folder to

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/table"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ScrollView>

</LinearLayout>

now we need some color and string definitions res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="app_name">Table</string>
	<color name="table_background">#999999</color>
	<color name="row_background">#ffffff</color>
</resources>

Downloads

Table.zip (Project files)
table

5 comments on “Android :: create dynamic table programmatically

  • Thank you for this great Solution!

    There is an error in layMain.addView(content.addRow(sFirstRow));
    Correct solution:
    layMain.addView(table.addRow(sFirstRow));
    Greeting form Germany

  • Hallo Lukas,
    danke für Dein Beispiel.
    Bei mir wird nur die erste Zeile dargestellt. Bei der zweiten gibt es folgenden exeption „Scroll View can host only one direct child“ was habe ich falsch gemacht?

    • Hallo Michael,

      danke für deinen Hinweis. Nachdem ich den Code überflogen habe, wundert es mich, dass er jemals funktioniert hat.
      Da meine Android-Erfahrung jetzt um zwei Jahre gewachsen ist, habe ich diese App mal auf den aktuellen Stand gebracht und die Projektdateien angehängt.

      Ich hoffe ich konnte dir helfen.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.