我想要一个带有 textview + 复选框的列表视图。我能够创建列表视图。我可以捕获列表视图项目选择。但是,当我尝试捕获复选框选择时,取消选择我得到一个空指针异常。如何为复选框编写 setOnCheckedChangeListener()..
public class LocationActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
final List<String> locLables = new ArrayList<String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.add(cursor.getString(1));
} while (cursor.moveToNext());
}
}
//String[] locLables = new String[] {"Home","University","Office"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locationmain_entry,R.id.textView12, locLables);
//cb gives a null pointer exception
CheckBox cb = (CheckBox) listview.findViewById(R.id.checkBox12);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("selected");
}else if(!isChecked){
System.out.println("not selected");
}
}
});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}