Blackberry获取ImageListField焦点索引

时间:2013-01-24 15:52:29

标签: listview blackberry java-me focus

我有ImageListField(自定义列表)。在菜单中我有删除选项我想删除列表中的任何元素。所以我设置了以下代码。我想获得具有焦点的元素的行索引...我将该元素ID传递给删除,然后进一步处理。

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);

它也被展示了3次。如何将它限制为1,而不是使用标志?

1 个答案:

答案 0 :(得分:1)

问题是你正在调用getFieldWithFocusIndex(),它是包含你的ImageListField 的类的方法,而不是ImageListField本身。

如果您有ManagerScreen,其中包含ImageListField,那么您要求该对象为其焦点字段。这可能总是返回list对象的索引。那是您不想要的整个列表。您需要该列表中的索引。所以,你需要一个不同的方法:

  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);

getSelectedIndex()对象上调用list应该有效。

至于为什么你看到方法被显示三次,这可能是因为有多种焦点事件。来自API docs on FocusChangeListener

  

static int FOCUS_CHANGED             提示事件的字段表示焦点发生变化   static int FOCUS_GAINED             提示该事件的现场已成为焦点   static int FOCUS_LOST             提示事件的字段已失去焦点。

如果您只想获得此通知一次,您可以添加对事件类型的检查(我不知道您是否正在调用标志,但这是最简单的方法这样做):

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

此外,也许这只是您为此问题发布的代码,但当然,您必须将重点索引存储在成员变量中。如果您只将其存储在本地index变量中,则稍后选择删除菜单项时,您的对象将无法使用该变量。