从游标填充AlertDialog。从所选项目中获取ID

时间:2012-04-20 20:38:02

标签: android cursor android-alertdialog

我正在制作我正在制作的游戏的设备屏幕。我让用户点击图片按钮。此按钮将显示从库存数据库填充的alertDialog。库存数据库具有字段(_id,Desc,Number,EquipSlot)。当用户单击我想要获取_id值的其中一个项目时,我就可以获得Number。从那里我将采用数字并交叉引用包含游戏中所有项目的数据库。这样我就可以找出附加到它的统计数据,以及更新存储字符信息的数据库以及当前使用的设备。我无法弄清楚如何让这个_id完成上述任务。以下是我到目前为止的情况。

 @Override
    protected Dialog onCreateDialog(final int id) {

      switch (id) {
      case DIALOG_MELEE_ID:
          buildDialog();
        break;
      case DIALOG_RANGE_ID:
          buildDialog();
        break;
     ...
      default:
          dialog = null;
              }
      return dialog;
    }

  @Override
    protected void onPrepareDialog(final int id, final Dialog dialog) {
      switch (id) {
      case DIALOG_MELEE_ID:
          pullInventoryCursor(1);
        break;
      case DIALOG_RANGE_ID:
          pullInventoryCursor(2);
        break;
     ...
      }
    }

    public void equipSlot1(View v){
        showDialog(DIALOG_MELEE_ID);
    }

    private void buildDialog(){
        int selectedItem = -1; //somehow get your previously selected choice
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select Weapon").setCancelable(true);
        builder.setSingleChoiceItems(inventory, selectedItem, "Desc", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                //get _id and update dbs as needed.
                dialog.dismiss();


            }
        });

        dialog = builder.create();
    }

    private void pullInventoryCursor(int equipSlot){
        if (slot == 1){
        inventory = mydbhelper.getInventory1(equipSlot);}
        else if (slot == 2){
            // TODO setup database and dbhelper for character slot 2
            inventory = mydbhelper.getInventory1(equipSlot);
        }
        startManagingCursor(inventory);
    }

1 个答案:

答案 0 :(得分:3)

您可以从对话框中提取列表视图,然后通过listview的适配器检索给定位置的项目的ID

builder.setSingleChoiceItems(inventory, selectedItem, "Desc", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                ListView lv = dialog.getListView();
                long itemId = lv.getAdapter().getItemId(which);

                //do whatever you need with the ID in the DB

                dialog.dismiss();


            }
        });

注意:显然

long itemId = lv.getItemIdAtPosition(which);

将与

相同
long itemId = lv.getAdapter().getItemId(which);
相关问题