2015-09-08 208 views
0

在下面的代碼中,我創建了一個字符串數組,並拆分字符串以去除ID。取而代之,我想要關聯數組,以便我可以從數組中選擇項目的ID。誰能幫忙!Android ListView獲取項目ID

String[] data={"12__Item 1","14__Item 2","34__Item 3","56__Item 4"}; 
lv = (ListView)findViewById(R.id.leaning_path_list_view); 

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.learning_path_single_row,R.id.textView,data); 
    lv.setAdapter(adapter); 


    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

      String item =(String)parent.getItemAtPosition(position); 
      String[] parts = item.split("__"); 

      Toast.makeText(getApplicationContext(), 
        "ID: " + parts[0]+" Title: " + parts[1], Toast.LENGTH_LONG) 
        .show(); 


     } 
    }); 
+0

你的代碼沒有開始新的活動,因爲startActivity(i);已被註釋掉 – Blackbelt

+0

對不起,我已更新問題 –

+0

請編輯您的問題,以清楚地顯示您的問題。 –

回答

1

試試這個:

public class YourItem { 

    private String title; 
    private long id; 

    public YourItem(long id, String title){  
     this.setTitle(title); 
     this.setId(id);    
    } 

    public String getTitle() { 
     return title; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 

    public long getId() { 
     return id; 
    } 

    public void setId(long id) { 
     this.id = id; 
    } 

    @Override 
    public String toString(){ 
     return title; 
    } 
} 

打電話給你的適配器是這樣的:

YourItem[] data={new YourItem(12,"Item 1"), 
       new YourItem(14,"Item 2") 
       new YourItem(34,"Item 3") 
       new YourItem(56,"Item 4") 
       }; 


ArrayAdapter<YourItem> adapter = new ArrayAdapter<YourItem>(this,R.layout.learning_path_single_row,R.id.textView,data); 

而在你的聽衆做這樣的事情:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

     String title= parent.getItemAtPosition(position).getTitle(); 
     long id = parent.getItemAtPosition(position).getId() 

     Toast.makeText(getApplicationContext(), 
       "ID: " + id +" Title: " + title, Toast.LENGTH_LONG) 
       .show(); 


    } 
}); 

我認爲它應該做到這一點。

+0

如果這對你有幫助,你應該接受答案,以便大家都知道你已經完成了這個問題。謝謝 –