focusable row inside table android

If you are asking about how to make table to behave like ListView, I did the following:

In xml-file, which defines layout for my Activity, I defined the table:

<ScrollView
    android:layout_height="wrap_content"
    android:layout_width="fill_parent" >
    <TableLayout
        android:id="@+id/my_table"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:stretchColumns="1"
        android:shrinkColumns="1"/>
</ScrollView>

Then, I wrote separate table_row_item.xml file with table row layout:

<?xml version="1.0" encoding="UTF-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:focusable="true"
    android:focusableInTouchMode="false"
    android:clickable="true"
    android:background="@android:drawable/list_selector_background">

    <TextView
        android:id="@+id/cell_1"
        ...
    />
    ...
    <TextView
        android:id="@+id/cell_N"
        ...
    />
</TableRow>

In Activity I declared procedure to add a row to my table:

private void addTableRow() {
    final TableLayout table = (TableLayout) findViewById(R.id.my_table);
    final TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.table_row_item, null);

    TextView tv;
    // Fill out our cells
    tv = (TextView) tr.findViewById(R.id.cell_1);
    tv.setText(...);
    ...
    tv = (TextView) tr.findViewById(R.id.cell_N);
    tv.setText(...);
    table.addView(tr);

    // Draw separator
    tv = new TextView(this);
    tv.setBackgroundColor(Color.parseColor("#80808080"));
    tv.setHeight(/*height of separaor line. 2dip will be enough*/);
    table.addView(tv);

    // If you use context menu it should be registered for each table row
    registerForContextMenu(tr);
}

Leave a Comment