2016-08-08 155 views
0

發生了一些奇怪的事情,當我點擊列表中的一行時,相應的複選框也被選中。所以一切都是正確的,但奇怪的是,自動每7行復選框setcheked爲true。 什麼問題?感謝您的幫助Android listview getView checkBox

ListAdapter adapter = new ArrayAdapter<Dettaglio1> 
      (this, R.layout.deteails_list_pdf, R.id.tv_nome_categoria, dettagli1) { 
@Override 
     public View getView(final int position, View convertView, ViewGroup parent) { 
      View row = super.getView(position, convertView, parent); 
... 
... 
list.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        final Dettaglio1 d1 = dettagli1.get(position); 

        d1.setChecked(!d1.isChecked()); 

        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox2); 
        checkBox.setChecked(d1.isChecked()); 

       } 
      }); 
      return row; 
     } 
    }; 
    list.setAdapter(adapter); 

private class Dettaglio1 { 
    String nome; 

    private boolean isChecked; 

    public void setChecked(boolean isChecked) { 
     this.isChecked = isChecked; 
    } 

    public boolean isChecked() { 
     return isChecked; 
    } 
} 
+0

你能發佈你的佈局文件嗎? – manfcas

回答

1

發生了什麼事被稱爲視圖回收 - 的核心機制背後ListViewRecyclerView。每7日檢測一次CheckBox,因爲這與CheckBox回收並顯示其以前的狀態相同。

要解決您的問題,您需要在數據模型(Dettaglio1類)中保持「已檢查」狀態。例如,你可以修改你的數據模型,如下所示:

public class Dettaglio1 { 
    // stuff 
    private boolean isChecked; 

    public void setChecked(boolean isChecked) { 
     this.isChecked = isChecked; 
    } 

    public void isChecked() { 
     return isChecked; 
    } 
    // more stuff 
} 

而且你的聽衆,像這樣:

@Override 
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    final Dettaglio1 d1 = dettagli1.get(position); 
    d1.setChecked(!d1.isChecked()); 

    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox2); 
    checkBox.setChecked(d1.isChecked()); 
} 

編輯: 您還需要重寫你的適配器的getView()方法,並設置CheckBox根據當前位置的Dettaglio1檢查狀態。

+0

此解決方案不能解決問題。我編輯了我的帖子 – user2847219

+0

哦,對。編輯我的帖子。 – npace