I am creating an Android application where I have a ListView that displays all of the applications that were installed in my mobile phone.
My ListView is customized,
Full reference present at : listview with checkbox android studio Pass selected items to next activity
Main source code is as below.
Create a model class first
public class Model {
private boolean isSelected;
private String animal;
public String getAnimal() {
return animal;
}
public void setAnimal(String animal) {
this.animal = animal;
}
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Then in adapter class, setTags to checkbox. Use those tags in onclicklistener of checkbox.
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList modelArrayList;
public CustomAdapter(Context context, ArrayList modelArrayList) {
this.context = context;
this.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.lv_item, null, true);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.checkBox.setText("Checkbox "+position);
holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
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 = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
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 tvAnimal;
}
}