繁体   English   中英

如何将数据库行ID分配给按钮

[英]How to assign database row id to a button

我正在遍历数据库中的行时创建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);
}

您可以使用View的setTag()和getTag()方法:标记基本上是一种允许视图存储一些其他数据的方法。 您可以使用以下方式存储ID:

delete_button.setTag(row_id);

在Button的侦听器中,您可以使用以下方法简单地检索ID:

Integer id = (Integer) delete_button.getTag();

然后执行您的逻辑应该对这条信息进行的处理。 在此处查看更多信息: https : //developer.android.com/reference/android/view/View.html#Tags

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM