2016-07-06 46 views
-1

我下面的教程here使複選框列表,我的適配器是這樣的:Android的ListView的回收機制

private class ViewHolder{ 
    CheckBox name; 
} 

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

    ViewHolder holder = null; 
    LayoutInflater settingInflater = LayoutInflater.from(getContext()); 
    if (convertView == null) { 
     convertView = settingInflater.inflate(R.layout.custom_row, parent, false); 
     holder = new ViewHolder(); 
     holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1); 
     convertView.setTag(holder); 

     holder.name.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       CheckBox cb = (CheckBox) v; 
       CustomCheckbox theCheckbox = (CustomCheckbox) cb.getTag(); 
       Toast.makeText(getContext(), 
         "Clicked on Checkbox: " + cb.getText(), 
         Toast.LENGTH_SHORT).show(); 
       Log.e(TAG,Integer.toString(position)); 

     }); 
    }else{ 
     holder = (ViewHolder)convertView.getTag(); 
    } 

} 

有我的屏幕上約15個條目,當我開始這個觀點,但是當我向下滾動並選擇第16個複選框,它的位置又回到零,下面的條目相應地變爲1,2,3等....我如何實現持有人,以便我可以獲得每個人的正確位置編號複選框?

謝謝!

+1

你需要保持在已檢查的人的位置名單 – tyczj

回答

0

的ListView回收觀點確實正在定義,只有當觀點是不回收的,所以當你點擊你點擊收聽「老」的聽衆依然活躍

if (convertView == null) { 
     //here you have new view 
     convertView = settingInflater.inflate(R.layout.custom_row, parent, false); 
     holder = new ViewHolder(); 
     holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1); 
     convertView.setTag(holder); 
    }else{ 
     //here you get recycled view 
     holder = (ViewHolder)convertView.getTag(); 
    } 
    //you should put you code here after you retrieve your view (either new or recycled) 
    holder.name.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      CheckBox cb = (CheckBox) v; 
      CustomCheckbox theCheckbox = (CustomCheckbox) cb.getTag(); 
      Toast.makeText(getContext(), 
        "Clicked on Checkbox: " + cb.getText(), 
        Toast.LENGTH_SHORT).show(); 
      Log.e(TAG,Integer.toString(position)); 

    });