Search code examples
javaandroidandroid-gridlayout

Android Studio > GridLayout > how to get the position of a cell?


<GridLayout
        android:id="@+id/gridLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_row="0"
            android:layout_column="0"
            android:onClick="markSquare" />

        <Button
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_row="0"
            android:layout_column="1"
            android:onClick="markSquare" />

        <Button
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_row="1"
            android:layout_column="0"
            android:onClick="markSquare" />

        <Button
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_row="1"
            android:onClick="markSquare" />

</GridLayout>

Description: Each button is inside a cell and points to a method called "markSquare", which looks like this:

public void markSquare(View v) {
}

How can I get the position of the "v" parameter? (the same position I specified in "layout_row" and "layout_column")


Solution

  • There is no direct way to get the position of the cell. However you use the view id to get exact view that click.

    1: Give the specific ids to the button.i.e button1, button2

    2:And check your view clicks id's like:

     public void markSquare(View v) {
        switch(v.getId()){
        case R.id.button1:{
        //Do here what you want
        break;
        }
    
        case R.id.button2:{
        //Do here what you want
    
        break;
        }
    
        }
     }