views:

407

answers:

1

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

A: 

Remove if (field == btn[context]) from your code .It will work. Enjoy now.

Santosh Kr. Jha
Thanks for taking some time out and helping me out with my problem and sorry for taking this long to get back at you.I have removed the "if" condition from my code and its working now but still I am not getting the desired output.When I am pressing the "Button 0" I am getting "Label 1" as the Output which is supposed to be "Label 0" that is the output should match the index of Button field.Is there any way to get just the index of Buttonfield instead of getting the index of all the fields on the screen. Like ButtonField.getindex().
Nikesh Yadav