Setting onClickListener to TableRow with TextViews

ClaireG picture ClaireG · Jul 30, 2013 · Viewed 15.8k times · Source

Good day to all.

I have a TableLayout with three TextViews in each of its rows. Is it still possible to add OnClickListener to the whole row? I'd like to change the background colour of the selected row. I've set an OnClickListener to the TableRow by doing the following, but the background colour doesn't change:

   for(int i =0; i < rowAmount; i++)
        {           
            TableRow tr= new TableRow(this);

            TextView rmNo;
            TextView s;
            TextView p;

            rmNo = new TextView(this);
            s = new TextView(this);
            p = new TextView(this);

            rmNo.setText("" + roomNumbers.get(i).toString());
            s.setText("" + statuses.get(i).toString());
            p.setText("" + priorities.get(i).toString());

            tr.addView(rmNo);
            tr.addView(s);
            tr.addView(p);      

            tr.setOnClickListener(new View.OnClickListener() 
            {                   
                @Override
                public void onClick(View v)
                {
                    tr.setBackgroundColor(color.holo_blue_light);
                }
            });

            tblContent.addView(tr);
        }

    }

I am creating the TableRows and TextViews programmaticaly because their data is retrieved from a database.

This is the XML:

<ScrollView
    android:id="@+id/scroll"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tblTitles">   
    <TableLayout 
        android:id="@+id/tblContent"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/ob">


   </TableLayout>
</ScrollView> 

Any help / ideas would be greatly appreciated.

Already looked-up sources:

How can I highlight the table row on click ?

How to change the background color of a TableRow when focused?

Answer

malimo picture malimo · Jul 30, 2013

i tested it, and now it works just fine, try using

tr.setOnClickListener(new View.OnClickListener() 
{                   
    @Override
    public void onClick(View v)
    {
        v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
    }
});

instead...