Reputation: 6249
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.
Upvotes: 2
Views: 182
Reputation: 1116
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);
}
});
Upvotes: 2
Reputation: 3411
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.
Upvotes: 2