Reputation: 9833
I'm creating a TableLayout UI while iterating over rows from the database. I want to have the functionality of removing a row from the UI as well as database on click of a button. How would I assign that id
to the button (perhaps as a button attribute) so that I can fetch it when it's clicked and run the database query?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.abc.def.FeedHistory">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="@+id/todayTable">
</TableLayout>
</RelativeLayout>
// result is a Cursor which contains x number of rows
TableLayout table = (TableLayout) findViewById(R.id.todayTable);
while(result.moveToNext())
{
int row_id = Integer.parseInt(result.getString(0));
String value_from_db = result.getString(1).toString();
TableRow row = new TableRow(this);
TextView row_text = new TextView(this);
row_text.setText(value_from_db+" units");
Button delete_button = new Button(this);
delete_button.setText("Remove");
// how to set row_id here?
// is it okay to use `setId()` method or is there a more elegant way, like a custom attribute?
row.addView(row_text);
row.addView(delete_button);
table.addView(row);
}
Upvotes: 0
Views: 69
Reputation: 577
You could use View's setTag() and getTag() methods: tag is basically a way to allow views to have memory of some additional piece of data. In your case you can store the id with:
delete_button.setTag(row_id);
In the listener of your Button you can retrieve the id simply with:
Integer id = (Integer) delete_button.getTag();
And then do what your logic is supposed to do with this piece of information. See more here: https://developer.android.com/reference/android/view/View.html#Tags
Upvotes: 1