2011-08-19 71 views
0

我有一個列表視圖裏面選中的文本視圖,每當我單擊列表中的項目查看隨機檢查的文本視圖將檢查(不neccessarily我按下了一個),這裏是我的代碼如何在列表視圖中訪問選中的文本視圖?

lv2.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      final CheckedTextView checkedTextView = (CheckedTextView) findViewById(R.id.checkedTextView1); 

      checkedTextView.toggle(); 

     } 
    }); 

凡LV2是我的列表視圖和checkedTextView1是我在每個listview項目中的檢查視圖。我如何調用特定的checkedTextView。有我可以調用的數組格式嗎?例如checkedTextView[1].toggle();?這裏

編輯是我的適配器

public class SpecialAdapter2 extends ArrayAdapter<String> { 

private int[] colors = new int[] { R.drawable.row_background_grey, 
     R.drawable.row_background_white }; 

public SpecialAdapter2(Context context, int resource, String[] names) { 
    super(context, resource, names); 
    // TODO Auto-generated constructor stub 
} 

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


    View view = super.getView(position, convertView, parent); 

    int colorPos = position % colors.length; 
    view.setBackgroundResource(colors[colorPos]); 
    return view; 
} 
+0

你不想檢查一個檢查或不?... – Dinash

+0

是的,我想查一個我檢查。但它檢查頂部一個(無論我檢查其相同的模式) – Sean

回答

1

嘗試改變onItemClick()的代碼到:

CheckedTextView checkedTextView = (CheckedTextView)arg1.findViewById(R.id.checkedTextView1); 
checkedTextView.toggle(); 

的問題是,你是隱式調用這個findViewById() - 即。你的活動。在您的活動上調用findViewById()將導致它搜索您的整個視圖層次結構中的第一個View,它可以使用id checkedTextView1查找它。這不是你想要的,但你想在被點擊的行項目中找到特定的CheckedTextView。因此需要在arg1上調用findViewById()

+1

嗨,我試過的代碼,但它出現了相同的錯誤。如果我沒有弄錯視圖是列表活動lv2而位置存儲爲int arg2。那麼有沒有代碼可以用arg2引用這個項目? – Sean

+0

你可能想要做的一件事是將參數從arg0等重命名爲更有意義的東西。在這種情況下,arg0是ListView,arg1是與被點擊的項目對應的視圖。您使用的是自定義適配器還是Android提供的適配器? – glorifiedHacker

+0

我貼了我的自定義適配器,它用於交替每個項目的背景顏色。 – Sean

1

試試這個

final CheckedTextView checkedTextView = (CheckedTextView) arg1; 
checkedTextView.toggle(); 
+0

是的,它完全在參數中 –

相關問題