android - Switch State Change Does Not Work On The First Click -
if change switch state databasereference
doesn't change previous value first time... if change same switch state 1 more time works perfectly. here code:
public sigadapter(context context, string[] web, integer[] imageid) { super(context, r.layout.list, web); this.context = context; this.web = web; this.imageid = imageid; } @override public view getview(final int position, view view, viewgroup parent) { databasereference databasereference1 = database.getreference("data").child(web[position1].replace("/","")); databasereference=databasereference1.child("switch"); viewholder viewholder=new viewholder(); view listitemview = view; if (listitemview == null) { listitemview = layoutinflater.from(getcontext()).inflate(r.layout.list, parent, false); viewholder.txttitle = (textview) listitemview.findviewbyid(r.id.text_view); viewholder.imageview = (imageview) listitemview.findviewbyid(r.id.image_view); viewholder.switch1 = (switch) listitemview.findviewbyid(r.id.switch_button); final viewholder finalviewholder = viewholder; viewholder.switch1.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { position1 = (integer)v.gettag(); finalviewholder.switch1.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { databasereference databasereference1=database.getreference("data").child(web[position1].replace("/","")); databasereference databasereference2=databasereference1.child("switch"); if (ischecked){ databasereference2.setvalue("on"); }else { databasereference2.setvalue("off"); } } }); } }); listitemview.settag(viewholder); } else { viewholder = (viewholder)listitemview.gettag(); } viewholder.switch1.settag(position); viewholder.txttitle.settext(web[position]); viewholder.imageview.setimageresource(imageid[position]); return listitemview; }
because setting oncheckedchangelistener
in onclicklistener
; oncheckchanged()
method gets called after first click (not on first click).
just use oncheckedchangelistener
start instead.
viewholder.switch1 = (switch) listitemview.findviewbyid(r.id.switch_button); switch1.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { position1 = (integer) buttonview.gettag(); databasereference databasereference1 = database.getreference("data").child(web[position1].replace("/","")); databasereference databasereference2 = databasereference1.child("switch"); if (ischecked){ databasereference2.setvalue("on"); } else { databasereference2.setvalue("off"); } } }
Comments
Post a Comment