问题
I am a noobie at android programming , I am using Android studio and I have a listview item containing two textviews and a checkbox. I am trying to create a listiview with checkboxes so when a click on a specific button I will get a list the names of the checked items . Tried looking for tutorials and other helpful things but just can't get it right. Thank You everyone :) This is my custom adapter for the listview:
public class postadapter extends ArrayAdapter<post> {
ArrayList<post> list = new ArrayList<post>();
Context context;
int layoutResourceId;
post data[] = null;
public postadapter(Context context, int layoutResourceId, ArrayList<post> list) {
super(context, layoutResourceId, list);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.list = list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
holder.txtdescription = (TextView) row.findViewById(R.id.textView2);
holder.chk = (CheckBox) row.findViewById(R.id.chkbox);
row.setTag(holder);
holder.chk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
post post1 = (post) cb.getTag();
post1.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder)row.getTag();
}
post post1 = list.get(position);
holder.txtTitle.setText(post1.getPostname());
holder.txtdescription.setText("מספר שומרים:"+post1.getnumberguards()+" משעה: "+post1.getstime()+" עד שעה: "+post1.getetime());
holder.chk.setChecked(post1.isSelected());
return row;
}
static class ViewHolder
{
TextView txtTitle;
TextView txtdescription;
CheckBox chk;
}
}
回答1:
You can maintain a boolean array of all the selected checkbox-
- Declare Boolean array in your adapter -
boolean[] checkBoxState - Initialize it in your adapter's constructor -
checkBoxState= new boolean[list.size()] Then use this array in your getView method -
holder.checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(((CheckBox)v).isChecked()) { checkBoxState[position]=true; } else { checkBoxState[position]=false; } } });Retrieve the position from this array (Here adapter is the object of your custom adapter) -
for(int k=0;k< adapter.checkBoxState.length ;k++) {
if(adapter.checkBoxState[k]==true) { }`
来源:https://stackoverflow.com/questions/25464570/getting-all-checked-items-from-listview-android