2012-04-20 106 views
0

我正在爲我正在製作的遊戲設備屏幕上工作。我讓用戶點擊一個圖像按鈕。此按鈕會調出一個從庫存數據庫填充的alertDialog。庫存數據庫具有字段(_id,Desc,Number,EquipSlot)。當用戶點擊其中一個項目時,我想獲得_id的值,這樣我就可以得到Number。從那裏我將採取數字和交叉引用我的數據庫包含遊戲中的所有項目。通過這種方式,我可以弄清楚附加了什麼樣的統計信息,以及更新存儲角色信息的數據庫以及當前正在使用的設備。我無法弄清楚如何得到這個_id來完成上述。以下是我到目前爲止。AlertDialog從光標填充。從選定的項目獲取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); 
    } 

回答

3

您可以從您的對話框拉列表視圖,然後檢索一個項目的ID在通過ListView的適配器

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); 
相關問題