How can I highlight the table row on click ?

Ravi picture Ravi · Nov 2, 2010 · Viewed 25.6k times · Source

As my project requirement i have to highlight the table row on onClick. There is any way to do this? Or please suggest me the alternative?

Answer

Salil Pandit picture Salil Pandit · Nov 20, 2011

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).