我發現很多答案都是不相關的,不符合與我有關的問題的觀點。列表視圖中的複選框有問題,在列表視圖的滾動過程中被選中時會隨機波動。ListVIew中的CheckBox使用SimpleCursorAdapter在滾動時被隨機選中
這是我的代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
DBMacros.getEntityList(this);
} catch (Exception e) {
}
m_cList = (ListView) findViewById(R.id.LIST_MAIN);
m_cCheckB = (CheckBox) findViewById(R.id.check_box);
m_cList.setSmoothScrollbarEnabled(true);
m_cObjNTable = new NamesTable();
m_cObjNTable.delete(this);
ArrayList<HashMap<String, String>> alist = new ArrayList<HashMap<String, String>>();
//Just once run. no debugging later
for (int i = 0; i < 30; i++) {
HashMap<String, String> hmap = new HashMap<String, String>();
m_cObjNTable = new NamesTable();
m_cObjNTable.setNames("name_" + i);
m_cObjNTable.save(this);
hmap.put("name_", "name_" + i);
alist.add(hmap);
}
m_cObjCursor = NamesTable.read(this);
m_cObjAdapter = new SimpleCursorAdapter(this, R.layout.cell, m_cObjCursor, new String[]{"Names", "Names"}, new int[]{ R.id.textview, R.id.check_box});
m_cAdapter = new CustomHourAdapter(this, R.layout.cell, alist);
m_cCheckBoxState = new boolean[alist.size()];
m_cObjAdapter.setViewBinder(this);
m_cList.setAdapter(m_cObjAdapter);
// m_cList.setAdapter(m_cAdapter);
}
@SuppressWarnings("unchecked")
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
boolean lRetVal = false;
String lVal = cursor.getString(columnIndex);
int lColIndex = cursor.getColumnIndex("Names");
if(lColIndex == columnIndex){
// Toast.makeText(this, "columnIndex = "+lVal+"" ,Toast.LENGTH_SHORT).show();
}
if(view.getId() == R.id.check_box) {
((CheckBox)view).setVisibility(View.VISIBLE);
lRetVal = false;
}else if (view.getId() == R.id.textview) {
// ((TextView)view).setText(lVal);
lRetVal = true;
Toast.makeText(this, "columnIndex = "+lVal+"" ,Toast.LENGTH_SHORT).show();
}
//Crashing as NullPointerException
try {
final int lposition1 = m_cList.getPositionForView((View) view.getParent());
Holder holder = null;
holder = new Holder();
holder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setTag(holder);
holder = (Holder) view.getTag();
holder.checkbox.setChecked(m_cCheckBoxState[lposition1]);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked())
m_cCheckBoxState[lposition1] = true;
else
m_cCheckBoxState[lposition1] = false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return lRetVal;
}
的主要問題是,我不會通過重寫setViewValue
得到這個職位,所以我用getPositionForView
這是給我一個nullPointer
。是否有任何其他方式可以通過SimpleCursorAdapter解決此問題。
在此先感謝
感謝您的回答。但是我在問題中已經清楚地解釋了它無法獲得視圖的位置,因爲無法使用SimpleCoursorAdapter重寫getView(),所以建議我使用其他任何資源。 –