Search code examples
androidandroid-tablelayout

Dynamically get position of row in android table layout


I have a table layout that gets dynamically filled with data the table contains 4 columns, 3 are text views and 1 is and image button

<TableLayout
    android:id="@+id/tablePicklist"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:stretchColumns="*">

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="code"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="desc"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="barcode"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="action"/>

    </TableRow>

</TableLayout>

on clicking the image button I want to get the position of the row of the table to access the row data I also do not want to set an id for the button as the rows will removed dynamically

I have tried to get row id by view id but it returns 1

ImageButton imgBtn = new ImageButton(context);
imgBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.e("table row", view.getId());
    }
});

also by trying the table row, it returns -1

ImageButton imgBtn = new ImageButton(context);
imgBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        TableRow tr = (TableRow) view.getParent();
        Log.e("table row", tr.getId());
    }
});

I think it is to do with the table layout but unsure of it

Thanks


Solution

  • Figured it out.

    got the solution from https://stackoverflow.com/a/34823284/10754488

    ImageButton imgBtn = new ImageButton(context);
    imgBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TableRow tr = (TableRow) view.getParent();
            int index = tableLayout.indexOfChild(row);
        }
    });