In my application I use this to count the checked checkbox in real time meaning when tick the box the count above will increase or decrease. but when scrolling down the listview
In your adapter object add a boolean parameter for check and un-check. By default set false for each item in the list, when checked set as true in adapter and call notifyDataSetChanged().
Use a model class
public class ContactModel {
String phone,name;
boolean sel;
public ContactModel(String phone, String name, boolean sel) {
this.phone = phone;
this.name = name;
this.sel = sel;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSel() {
return sel;
}
public void setSel(boolean sel) {
this.sel = sel;
}
My custom adapter
public class ContactADAPTER extends BaseAdapter {
String phone,name;
boolean sel;
Activity act;
List contactModels;
public ContactADAPTER(Activity act, List contactModels) {
this.act = act;
this.contactModels = contactModels;
}
@Override
public int getCount() {
return contactModels.size();
}
@Override
public Object getItem(int i) {
return contactModels.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater=LayoutInflater.from(context);
view=inflater.inflate(R.layout.phone_list_item,viewGroup,false);
TextView phone1= (TextView) view.findViewById(R.id.phone1);
TextView name1= (TextView) view.findViewById(R.id.name1);
CheckBox tick= (CheckBox) view.findViewById(R.id.tick);
phone1.setText(contactModels.get(i).getPhone());
name1.setText(contactModels.get(i).getName());
if(contactModels.get(i).isSel())
{
tick.setSelected(true);
}
else
{
tick.setSelected(true);
}
tick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
contactModels.get(i).setSel(isChecked);
notifyDataSetChanged();
//for getting ticked count
int count=0;
for(ContactModel c:contactModels)
{
if(c.isSel())
{
count++;
}
}
// show count
act.getActionBar().setTitle(String.valueOf(count));
}
});
return view;
}
}
In Activity
List cmodelList= new ArrayList<>();
cmodelList.add(new ContactModel(phonenumber, name, false));
cmodelList.add(new ContactModel(phonenumber2, name2, false));
cmodelList.add(new ContactModel(phonenumber3, name3, false));
ContactADAPTER contactAdapter=new ContactADAPTER(Phone_Contact_List.this,cmodelList);
listView.setAdapter(contactList);