我在迭代数据库中的行时创建了一个TableLayout UI。我希望具有从UI中删除行的功能以及单击按钮时的数据库。如何将id
分配给按钮(可能作为按钮属性),以便在单击并运行数据库查询时可以获取它?
<?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);
}
答案 0 :(得分:1)
你可以使用View的setTag()和getTag()方法:tag基本上是一种允许视图拥有一些额外数据的方式的方法。 在您的情况下,您可以使用以下内容存储ID:
delete_button.setTag(row_id);
在Button的监听器中,只需使用以下命令检索id:
Integer id = (Integer) delete_button.getTag();
然后做你的逻辑应该对这条信息做什么。 在这里查看更多: https://developer.android.com/reference/android/view/View.html#Tags