问题是您正在调用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.