how to implement "select/unselect all" checkbox in android -


i want implement 1 code have checkbox's item , if select items checked , wants print checked item on single string. below code checkbox. want add "all" in string employed works select item.

public class mainactivity extends listactivity { 

string array used datasource arrayadapter of listview

string[] employed = new string[] {         "government",         "army officer",         "merchant navy",         "shipping",         "professor",         "teacher",         "doctor",         "dentist",         "chartered accountant" }; 

called when activity first created.

   @override    public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main); 

defining array adapter store items listview

    final arrayadapter<string> adapter = new arrayadapter<string>(this,      android.r.layout.simple_list_item_multiple_choice, employed); 

setting arrayadapter listview

 getlistview().setadapter(adapter); 

defining checkbox click event listener

      onclicklistener clicklistener = new onclicklistener() {         @override         public void onclick(view v) {             checkbox chk = (checkbox) v;             int itemcount = getlistview().getcount();             for(int i=0 ; < itemcount ; i++) {                 getlistview().setitemchecked(i, chk.ischecked());             }         }     }; 

defining click event listener listitem checkbox

  onitemclicklistener itemclicklistener = new onitemclicklistener() {          @override         public void onitemclick(adapterview<?> arg0, view arg1, int arg2,          long arg3) {             checkbox chk = (checkbox) findviewbyid(r.id.chkall);             int checkeditemcount = getcheckeditemcount();              if(getlistview().getcount()==checkeditemcount)                 chk.setchecked(true);             else                 chk.setchecked(false);         }     }; 

getting reference checkbox available in main.xml layout

  checkbox chkall =  ( checkbox ) findviewbyid(r.id.chkall); 

setting click listener checkbox

 chkall.setonclicklistener(clicklistener); 

setting click listener listitem checkbox

getlistview().setonitemclicklistener(itemclicklistener);  } 

returns number of checked items

 private int getcheckeditemcount(){     int cnt = 0;     sparsebooleanarray positions = getlistview().getcheckeditempositions();     int itemcount = getlistview().getcount();      for(int i=0;i<itemcount;i++){         if(positions.get(i))             cnt++;     }     return cnt;    }  }    


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -