Hi,
I am adding dynamic number of buttons in a Blackberry application and trying to get different events on each button click. I am not able to apply the setchangelistener() for these array of buttons as once the loop finishes after adding all the buttons, the events gets generated only for the last indexed button.
If I make us of getIndex(), it runs fine only if I am not adding any other fields on my screen, but if I add other fields along with these array of buttons, the getIndex() function count them in the indexing as well.
Can anyone please help me out in setting FieldChangeListener to array of ButtonField?
Here is a sample code of the way I am using the array of ButtonField. I the code I have added two test LabelField at the top of the screen, if I remove them the code will run fine and I will get different result for each button click, but if I keep them active, the indexing gets effected and the Button wont work.
package buttonclickloop;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class ButtoncClickLoop extends MainScreen {
int i = 0;
private ButtonField[] btn = new ButtonField[50];
public ButtoncClickLoop() {
// TODO Auto-generated constructor stub
LabelField Field1 = new LabelField("Field1");
LabelField Field2 = new LabelField("Field2",DrawStyle.RIGHT | ButtonField.USE_ALL_WIDTH);
HorizontalFieldManager FieldHmgr = new HorizontalFieldManager();
FieldHmgr.add(Field1);
FieldHmgr.add(Field2);
FieldHmgr.setMargin(0,0,10,5);
add(FieldHmgr);
while (i < 3){
FieldChangeListener listener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
context = field.getIndex();
if (field == btn[context]){
add(new LabelField("Label" + context + ""));
}
}
};
btn[i] = new ButtonField("Button" + i + "");
btn[i].setChangeListener(listener);
add(btn[i]);
i = i + 1;
}
}
}
Thanks,
Nikesh