Android GridLayout get row/column

VoidCatz picture VoidCatz · Apr 18, 2014 · Viewed 12k times · Source

I have a 3x3 GridLayout with buttons. These buttons have a onTileClicked() listener. Now I want to get the position of the clicked button in the grid. Here is my code:

public void onTileClicked(View view) {
    Button button = (Button) view;
    GridLayout.LayoutParams params = (LayoutParams) button.getLayoutParams();
}

But how can i get the row and column of the clicked button? There is params.columnSpec but I don't know what to do with this...

Answer

AmmarCSE picture AmmarCSE · Apr 18, 2014

There is no direct way to get the position of the cell. However, you can calculate the position of the clicked button assuming you know the number of columns and rows in the onItemClick listener:

    public void onItemClick(AdapterView parent, 
         View v, int position, long id) 
    {   
        int row_no=position/3;
        int col_no=position%3;
        .
        .
    }