Codename One - Correct use of the Picker

五迷三道 提交于 2019-12-10 11:00:02

问题


I'm trying to do a clear question about the use of the Picker, because my previous one in not enough clear: Codename One - addActionListener of a Picker

The purpose of the Picker is to select one element from a set, such as a string of a set of strings, is it right? So, I want to give the user the opportunity to select a string from a set of strings, each of one corresponds to a language.

The problem is that the use of an ActionListener added to the Picker is not correct for this purpose, because it's triggered by both "Ok" and "Cancel" buttons.

I need to execute some code (to change the language) only and only if the user press "Ok", because executing that code if the user press "Cancel" should be considered an unexpected behavior and a bug (from the point of view of the user).

So my question is how to use correctly the Picker in this use case.


回答1:


From the CN1 documentation, one way to do this would be :

String [] list = {"one" , "two" , "three"};
Picker picker = new Picker ();
picker.setType(Display.PICKER_TYPE_STRINGS);
picker.setStrings(list);
picker.setSelectedString("test");

picker.addActionListener(l -> System.out.println(picker.getSelectedString()));

Oddly, and as Francesco has pointed out in a prior moment, when you run the application IN THE SIMULATOR, and press the Cancel-Button inside the picker, it prints out the selected string. Same when you press the OK-Button. (Is this intended?)

On installed devices, the results seem to be mixed, as to on some devices the cancel operation does not incur in any action.




回答2:


I had to do this to avoid triggering another listener on the string (I was using a Property with a change listener) if Cancel was pressed, and I did this by checking the current picker string against the previous selected string to see if it changed. I only updated the field or local variable (Property in my case) if the value changed. Modifying the previous answer's code:

...
private String currentSelection;
...

String [] list = {"one" , "two" , "three"};
Picker picker = new Picker ();
picker.setType(Display.PICKER_TYPE_STRINGS);
picker.setStrings(list);
picker.setSelectedString("test");

picker.addActionListener(l -> {
   if (!picker.getSelectedString.equals(currentSelection) {
      currentSelection = picker.getSelectedString;
      System.out.println(currentSelection);
   }
});


来源:https://stackoverflow.com/questions/49733763/codename-one-correct-use-of-the-picker

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!