簡體   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