我有一个自定义列表视图,其中的每一行都由文本视图和复选框组成。(1)当我单击列表中的项目时,它应该转到其他活动和(2)当复选框被选中时,文本视图中的值应该被添加到数组中//当它未被选中时,值应该从数组中删除。第一个要求与我一起成功运行,但第二个要求不起作用。这是我的代码:
public class DataAdapter extends ArrayAdapter<ItemInList> {
public ArrayList<ItemInList> list;
public Activity context;
public LayoutInflater inflater;
public static ArrayList<String> array=new ArrayList<String>();
ItemInList element=new ItemInList();
public DataAdapter(Activity context,int x,ArrayList<ItemInList> list) {
super(context, 0, list);
this.context = context;
this.list = list;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
protected TextView name,Description;
protected CheckBox checkbox;
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public ItemInList getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.name = (TextView) convertView.findViewById(R.id.food_title);
holder.name.setTextColor(Color.BLACK);
holder.Description = (TextView) convertView.findViewById(R.id.food_description);
holder.Description.setTextColor(Color.GRAY);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.add_food_item);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
element = (ItemInList) holder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
if(element.isSelected())
{
array.add(element.getName());
}
else
{
array.remove(position);
}
}
});
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
ItemInList bean = (ItemInList) list.get(position);
holder.name.setText( bean.getName());
holder.Description.setText( bean.getDescription()+"");
holder.checkbox.setChecked( bean.isSelected());
return convertView;
}
holder.name.setText(list.get(position).getName());
holder.Description.setText(list.get(position).getDescription()+"");
holder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
错误:
null pointer exception..
at DataAdapter$1.onCheckedChanged(DataAdapter.java:92)
E/AndroidRuntime(543): at android.widget.CompoundButton.setChecked(CompoundButton.java:125)
E/AndroidRuntime(543): at sehaty.com.DataAdapter$1.onCheckedChanged(DataAdapter.java:92)
E/AndroidRuntime(543): at android.widget.CompoundButton.setChecked(CompoundButton.java:125)
at android.widget.CompoundButton.performClick(CompoundButton.java:99)
任何帮助将不胜感激