1

I am new to Android development and I am trying to handle clicks on a grid of items. What is the best way to do that? So far I have something like this to set the onclicklistener:

 TableLayout layout = (TableLayout) findViewById(R.id.tableLayout1);
    for (int i = 0; i < layout.getChildCount(); i++) {
        View v = layout.getChildAt(i);
        if (v instanceof TableRow) {
            for (int j = 0; j < ((TableRow)v).getChildCount(); j++) {
                View v2 =  ((TableRow)v).getChildAt(j);
                v2.setOnClickListener(this);
            }
        }
    }

Now I want to handle the clicks on the items contained in the table. As there are many items I want to avoid writing a long "switch". The items have logical IDs containing the number of the row and the column. Is there a way to get the actual ID of the item that has been clicked (the ID in the XML) and then parse it? If not, what would be the solution.

Thanks

mmBs
  • 8,421
  • 6
  • 38
  • 46
André
  • 287
  • 2
  • 16

1 Answers1

0

You have a few options. You can set the onClickListener inline:

v2.setOnClickListener(new OnClickListener() {
    public void onClick (View viewClicked) {
        Log.d("View row: " + i + ", column: " + j);
        // or something else
    }
});

Or you can use the View.setTag(), which will allow you to store key-value pairs to the view, similar to a map.

John Leehey
  • 22,052
  • 8
  • 61
  • 88