0

我有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?

4

1 回答 1

1

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

如果您有 aManager或 a Screen,其中包含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对象应该可以工作。

至于为什么你看到方法被显示了三遍,那可能是因为有多种焦点事件。来自FocusChangeListener 上的 API 文档

static int FOCUS_CHANGED 提示事件的字段表示焦点的变化。
static int FOCUS_GAINED 提示事件获得焦点的字段。
static int FOCUS_LOST 提示事件失去焦点的字段。

如果您只想收到此通知一次,则可以添加对事件类型的检查(我不知道这是否是您所说的flags,但这是最简单的方法):

    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.

于 2013-01-24T22:04:10.357 回答