在listview android中运行复选框时出错

书到用时方恨少,事非经过不知难。这篇文章主要讲述在listview android中运行复选框时出错相关的知识,希望能为你提供帮助。
当我在listview中尝试教程复选框时,我的适配器出现了一些错误

public View getView(int position, View convertView, ViewGroup parent) {ViewTag viewTag; if (convertView == null) { //取得listItem容器 view convertView = myInflater.inflate(R.layout.list_item_pegawai, null); //建構listItem內容view viewTag = new ViewTag( (TextView) convertView.findViewById(R.id.txt_namapegawai), (CheckBox) convertView.findViewById(R.id.checkBox_pegawai)); //設置容器內容 convertView.setTag(viewTag); } else { viewTag = (ViewTag) convertView.getTag(); }

答案【在listview android中运行复选框时出错】完整的代码
public class CustomAdapter extends BaseAdapter { private Context context; public static ArrayList< Model> modelArrayList; public CustomAdapter(Context context, ArrayList< Model> modelArrayList) { this.context = context; CustomAdapter.modelArrayList = modelArrayList; }@Override public int getViewTypeCount() { return getCount(); }@Override public int getItemViewType(int position) {return position; }@Override public int getCount() { return modelArrayList.size(); }@Override public Object getItem(int position) { return modelArrayList.get(position); }@Override public long getItemId(int position) { return 0; }@Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item_select, null, true); holder.checkBox = convertView.findViewById(R.id.checkBox); holder.tvName = convertView.findViewById(R.id.textView7); holder.Tvnumber = convertView.findViewById(R.id.textView8); convertView.setTag(holder); } else { // the getTag returns the viewHolder object set as a tag to the view holder = (ViewHolder) convertView.getTag(); }holder.tvName.setText(modelArrayList.get(position).getName()); holder.Tvnumber.setText(modelArrayList.get(position).getPhone()); holder.checkBox.setChecked(modelArrayList.get(position).getSelected()); holder.checkBox.setTag(R.integer.btnplusview, convertView); holder.checkBox.setTag(position); holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview); TextView tv = tempview.findViewById(R.id.textView7); Integer pos = (Integer) holder.checkBox.getTag(); if (modelArrayList.get(pos).getSelected()) { modelArrayList.get(pos).setSelected(false); } else { modelArrayList.get(pos).setSelected(true); } } }); return convertView; }private class ViewHolder { protected CheckBox checkBox; private TextView tvName; private TextView Tvnumber; }}


    推荐阅读