2013-04-28 57 views
1

我有一個ListView,每行一個按鈕。如果我需要得到的數據行被點擊的時候,那麼這將是很容易做到的onItemClickListener內的以下內容:單擊ListView的子項時從ListView獲取數據

 @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      CustomType type = (CustomType) arg0.getItemAtPosition(arg2);  //get data related to position arg2 item 
     } 
    }); 

其實,事情是,我需要得到的數據(即:CustomType對象)當ListView的行get按鈕被點擊時,而不是行本身。由於OnClickListener沒有像AdapterView這樣的參數(顯然是),我想知道我該如何處理這個? 到目前爲止,它發生在我得到按鈕的父母,這是列表視圖,並以某種方式進入最左邊的位置點擊按鈕,然後 調用類似於: myAdapter.getItem(position); 但是隻是一個想法,所以請,我會很感激這裏的一些幫助。

在此先感謝。

回答

4

你可能使用你的ListView所以最簡單的方式自定義適配器做你想要的目標是在的的getView()方法來設置將position參數適配爲Button的標籤。然後,您可以檢索在OnClickListener標籤然後您就會知道點擊了哪個行:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    //... 
    button.setTag(Integer.valueOf(position)); 
    button.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
       Integer rowPosition = (Integer)v.getTag(); 
     } 
    }); 
    //... 
} 

你也可以從該行的觀點中提取數據。這將工作,如果一切該行的數據可以從該行的觀點中找到:

button.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
      LinearLayout row = (LinearLayout)v.getParent(); I assumed your row root is a LinearLayout 
     // now look for the row views in the row and extract the data from each one to 
     // build the entire row's data 
    } 
}); 
0

添加一個自定義的方法在適配器返回CustomType

public CustomType getObjectDetails(int clickedPosition){ 
     CustomType customType = this.list.get(clickedPosition); 
     return customType ; 
    } 


public void onItemClick(AdapterView<?> arg0, View arg1, int Position,long arg3) { 
      CustomType type = getObjectDetails(Position); 
    } 
    }); 
+0

我需要做類似的東西里面按鈕的單擊事件監聽器和ListView不onItemClick監聽器 – Daniel 2013-04-28 07:50:04