Checkbox[] With Onclicklistener[]?
Solution 1:
Don't use anonymous (inline) listeners in this case. Instead have your Activity implement the listener...
publicclassMyActivityextendsActivityimplementsView.OnClickListener {
...
@OverridepublicvoidonClick(View v) {
switch (v.getId()) {
case impactsv[0].getId:
impactsb[0] = !impactsb[0];
...
break;
// Add other cases here
}
}
}
Then all you need to do to set the listener is...
impactsc[i].setOnClickListener(this);
Then test for which CheckBox has been clicked by using the View which is passed to...
onClick(View v)
Solution 2:
first you don't have to have them as final, you can declare them outsid of the function then you won't be asked to declare them as final. second if you need to know the state of the checkboxes as they are changed you can add a listener to each one of them with different task of course, you can do it with a loop, and then this loop will call to another function that will have the tag of this chsckbox, and will react according to this tag. If you don't need to know the state when they are changed you can check the state of them once you are done with this screen, with isSelected() method.
Hope this helps, Best regards.
Solution 3:
Here you go a complete code for this just fill between for your needs :
public class mainA extends Activity { CheckBox[] chbx;Button apply;
publicvoidOnCreate(Bundle bundle)
{ super.onCreate(bundle);
setMyChBx();apply=newButton(this);
apply.setOnClickListener(newView.OnClickListener()
{ publicvoidonClick(View v)
{ if(chbx[0].isSelected()) setsomthing0();
if(chbx[1].isSelected()) setsomthing1();
if(chbx[2].isSelected()) setsomthing2();
if(chbx[3].isSelected()) setsomthing3(); // and so on
}
});
}
publicvoidsetMyChBx()
{ chbx=newCheckBox[25];
for(int i=0;i<25;i++)
{ chbx[i]=newCheckBox(this);
chbx[i].setTag(newInteger(i));//tags for the checkboxes simply from 0 to 24 (24 included)
chbx[i].setOnClickListener(newchBxOnclick());
}
}
/*
* here you have three options to create one onclick method to all of them or to create many onclicks for each on of them
* or don't create onclick method for the checkboxes just check the state once it's all done like above
* example for onclick for all of them
*/publicclasschBxOnclickimplementsOnClickListener
{ publicvoidonClick(View v)
{ switch((Integer)v.getTag())
{ case0: dosomething();break;
case1: dothis();break;
case2: dathat(); break;
.
.
.
case24: doFor24();break;
}
}
}
}
Post a Comment for "Checkbox[] With Onclicklistener[]?"