Ahmad Shahwaiz
Ahmad Shahwaiz

Reputation: 1492

Blackberry Get ImageListField focus Index

I have ImageListField (custom list). In the menu I have Delete Option I want to delete any element in the list. So I have set the following code. I want to get the row Index of the element which has focus ... I will pass that element ID to delete and then process further.

public FocusChangeListener listFocus = new FocusChangeListener(){ 
        public void focusChanged(Field field, int eventType) {
            int index = getFieldWithFocusIndex(); 

            Dialog.alert("Index: "+index);
            // But its not giving the specific row index.
        }
    };
list.setFocusListener(listFocus);

Also It is being shown 3 times. How to limit it to 1, other than using flags?

Upvotes: 0

Views: 83

Answers (1)

Nate
Nate

Reputation: 31045

The problem is that you are calling getFieldWithFocusIndex(), which is a method of the class that contains your ImageListField, not the ImageListField itself.

If you have a Manager, or a Screen, that contains the ImageListField, then you are asking that object for its field with focus. That will probably always return the index of your list object. That's the whole list, which you don't want. You want the index of the row within that list. So, you need a different method:

  FocusChangeListener listFocus = new FocusChangeListener() { 
     public void focusChanged(Field field, int eventType) {
        //int index = getFieldWithFocusIndex(); 
        int index = list.getSelectedIndex();
        System.out.println("Index: " + index + " event: " + eventType);
     }
  };
  list.setFocusListener(listFocus);

Calling getSelectedIndex() on your list object should work.

As to why you see the method being shown three times, that's probably because there are multiple kinds of focus events. From the API docs on FocusChangeListener:

static int FOCUS_CHANGED Field prompting the event signals a change in focus.
static int FOCUS_GAINED Field prompting the event has gained the focus.
static int FOCUS_LOST Field prompting the event has lost the focus.

If you only want to get this notification once, you could add a check for the event type (I don't know if that's what you're calling flags, but that's the easiest way to do this):

    public void focusChanged(Field field, int eventType) {
        if (eventType == FocusChangeListener.FOCUS_CHANGED) {
           int index = list.getSelectedIndex();
           System.out.println("Index: " + index + " event: " + eventType);
        }
    }

Also, maybe this is just in the code you posted for this question, but of course, you will have to store the focused index in a member variable. If you only store it in the local index variable, that won't be available to your object when the Delete menu item is selected later.

Upvotes: 1

Related Questions