[英]How to assign database row id to a button
I'm creating a TableLayout UI while iterating over rows from the database. 我正在遍历数据库中的行时创建TableLayout UI。 I want to have the functionality of removing a row from the UI as well as database on click of a button. 我希望具有单击按钮即可从UI以及数据库中删除行的功能。 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? 我将如何将该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);
}
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. 您可以使用View的setTag()和getTag()方法:标记基本上是一种允许视图存储一些其他数据的方法。 In your case you can store the id with: 您可以使用以下方式存储ID:
delete_button.setTag(row_id);
In the listener of your Button you can retrieve the id simply with: 在Button的侦听器中,您可以使用以下方法简单地检索ID:
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 在此处查看更多信息: https : //developer.android.com/reference/android/view/View.html#Tags
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.