How can I highlight the table row on click ?
If you want to use the stock on click highlight like you get with a generic ListView, you want to set the background of each row to be android:background="@android:drawable/list_selector_background"
Here is an example:
<TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0"> <TableRow android:id="@+id/first_row" android:background="@android:drawable/list_selector_background" > ... row content ... </TableRow></TableLayout>
Then in code,
TableRow firstRow = (TableRow) findViewById(R.id.first_row);firstRow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO: do your logic here } }
And you should get a highlight-able row just like in a ListView...
EDIT:Above will give you the default theme's list background selector. If you want the more generic selector (like the material design selector when the user touches a row) use this:
android:background="?android:attr/selectableItemBackground"
Also this applies to more than just TableRows. You should be able to do this on almost any generic widget with an onClickListener attached (TextViews, Buttons, etc).
Even I was facing the same problem with the help of salil pandit answer made a little change to it and that works for me
This is TableRow
in xml:
<TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:padding="5dip" android:background="@drawable/selector">
This is selector.xml
in res\drawable
folder
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_focused="true" android:state_pressed="true" android:drawable="@android:drawable/list_selector_background"></item> <item android:state_focused="true" android:state_pressed="false" android:drawable="@android:drawable/list_selector_background"></item> <item android:state_focused="false" android:state_pressed="true" android:drawable="@android:drawable/list_selector_background" /> <item android:drawable="@android:drawable/list_selector_background"></item></selector>
Within the onclicklistener add:
tr1.setBackgroundResource(drawable.list_selector_background);
Where tr1 is your tablerow. (you will need to make the tablerow final for it to work).