2013-10-10 20 views
-2

我通過一個循環創建列表Item這樣的:選擇項目列表中的項目的Android

private void addItemToList(ItemRepository lst) 
{  
    //Add item to list 
    for(Item itm:lst.getItems()) 
    { 
     addItem(itm); 
    } 
} 

private void addItem(Item itm) 
{    
    View item = UtilMPos.getViewFromInflater(R.layout.item,Payment_ListItem.this); 
    TextView lblItemName = (TextView)item.findViewById(R.id.inv_lblitemname); 
    TextView lblItemDes = (TextView)item.findViewById(R.id.inv_lblitemdesc); 
    TextView lblPrice = (TextView)item.findViewById(R.id.inv_lblValueItem); 

    //Set value for text view 
    lblItemName.setText(itm.getItemName()); 
    lblItemDes.setText(itm.getItemDes()); 
    lblPrice.setText(Double.toString(itm.getPrice())); 

    //----process component item in here 
    llstItem.addView(item);    
} 

然後顯示(我用的LinearLayout顯示列表項):

------------------------------------------------------ 
item_name 1        Price 
item_descripton 
------------------------------------------------------ 
item_name 2        Price 
item_descripton 
------------------------------------------------------ 
item_name 3        Price 
item_descripton 
------------------------------------------------------ 

當點擊行,該行將被選中(粗體行或類似的東西),我可以得到該行的所有數據,例如:單擊行item_name 1,我得到所有數據行1.

+0

你能改述最後一部分,我是一隻半死的貓,但我無法制造它的頭或尾。 – Johan

+0

我編輯它,你能理解嗎? – lonelyboy0212

回答

0

你知道「OnClickListener」嗎?

樣品:

public class Main extends Activity implements OnClickListener { 

    ... 
    View item = ...findViewById(...); 
    item.SetOnClickListener(this); 
.... 


    @Override 
    public void onClick(View v) { 

    switch (v.getId()) { 
    case R.id.item_name1: 
     // do something 
     break; 
    case R.id.item_name2: 
     // do something 
     break; 
    } 

    } 


} 

希望這有助於。

+0

是的,我知道OnClickListener,但我創建列表項是動態的 - >我不能爲每個視圖添加動態ID,以及如何當列表項有很多很多項目,我們不能切換...案例 – lonelyboy0212

+0

然後爲什麼不使用ListActivity與自定義適配器?你會有一個「OnItemClicked」 - 事件。 – nouseforname

+0

嗨,感謝nouseforname,我用自定義listview,它工作正常,我解決了我所有的問題 – lonelyboy0212

1

創建一個標籤對象,並將itemName,itemDesc,price字段放入其中。 最後做到這一點:

item.setTag(tagObjCreated); 

而當你點擊該項目,並取回在OnClickListener(視圖),訪問這樣的標籤:

tagObjRetrieved = itemView.getTag(); 

並取回ITEMNAME,itemDesc ,您需要的價格字段。

HTH。

+0

你能解釋更多嗎?,所以爲了輕鬆想象,它看起來像Android上的列表聯繫人(顯示數據是相同的),當我點擊一個聯繫人,我會得到該聯繫人的所有信息 – lonelyboy0212

+0

列表中的每個項目都是一個視圖,對不對?所以,我建議你創建一個標籤對象(http://developer.android.com/reference/android/view/View.html#setTag(int,%20java.lang.Object),並將其填充到當你正在顯示和點擊列表中的項目時,如果你正在使用適配器,則在項目或OnItemClick的onclick(http://developer.android.com/reference/android/widget/AdapterView。 OnItemClickListener.html),你會看到回來的視圖,你回來的視圖,取回標籤,並檢索你填入標籤(姓名,desc,價格)的數據HTH –

+0

我強烈建議你使用SimpleAdapter或者一些與你的ListView一起使用的東西。在SDK的示例目錄中有一些例子。看看它。如果可以避免的話,不要試圖創建自己的List實現。 –

0

我找到了解決方案。我使用了自定義listview,它工作正常,我解決了我所有的問題。