2010-08-12 98 views
2

我有一個ListActivity,其中列表項是在另一個XML佈局中定義的。列表項目佈局包含一個ImageView,一個複選框,一個TextView等等。將onClick處理程序添加到列表項中查看

我想要的是將onClick偵聽器設置爲每個列表項中的CheckBox。這很簡單。麻煩的是我需要onClick處理程序來知道列表中的哪個位置。

我將偵聽器連接到getView中的CheckBox後,convertView已被充氣。 getView方法有一個位置參數,但我不能在我的CheckBox的onClick處理程序中引用它。我明白爲什麼,但我不知道如何解決這個問題。

我該如何做到這一點?

回答

1

我創造了這個方法來獲取位置:

private int getListPosition(View v) { 
     View vParent = (View)v.getParent(); 
     if (vParent != null) { 
      ViewGroup vg = (ViewGroup)vParent.getParent(); 
      if (vg != null) { 
       return getListView().getFirstVisiblePosition() + vg.indexOfChild(vParent); 
      } 
     } 
     return -1; 
    } 

你會在buttonView通過爲v參數

0

你可以嘗試通過它的位置,而當onCheckedChangeListener被炒魷魚,得到複選框的標籤來獲取其位置上的複選框設置標籤..

這裏是一個示例代碼,但我沒有試過它

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

// grab view 
View v = convertView; 
// set view layout 
if (v == null) { 
    LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    v = vi.inflate(R.layout.layout_inbox_item, null); 

    CheckBox box = (CheckBox)v.findViewById(R.id.inbox_itemcheck); 
    if (box != null) { 
     box.setTag(position); //<-- sets the tag by its position 
     box.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { 
       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
        int position = (Integer)buttonView.getTag(); //<-- get the position 
       } 
      }); 
    } 
} 
+0

有人發佈此解決方案,然後刪除解決方案,一旦我提出了我的問題。我的問題是我的列表可以被用戶改變(例如:刪除一行)。這會混淆刪除行下面的行的所有索引。 – Andrew 2010-08-13 13:57:49

+0

我想不出比您提供的更簡單的解決方案。如果我是你,我會去那個。 – capecrawler 2010-08-26 08:12:05

相關問題