This demo shows off an ability often requested by people, searching within a list without actually using a text field that "steals" the focus. As you can see a standard LWUIT text field is drawn on top of the List and accepts user input as it always does thus allowing me to narrow my search within a large unordered list.
This is accomplished rather easily by painting the text field on top of the list and redirecting game key events to the list while all others are sent to the text field.
The text field is hidden after 1000 milliseconds of no activity, no need for glasspane or anything of that magnitude. You do need the latest LWUIT trunk for this to work since text field assumed it has a parent from when getting input (which isn't the case here). To workaround this you can override install/remove commands in text field with an empty implementation.
List l = new List(LIST_DATA) {
private long lastSearchInteraction;
private TextField search = new TextField(3);
{
search.getSelectedStyle().setBgTransparency(255);
search.setReplaceMenu(false);
search.setInputModeOrder(new String[]{"Abc"});
search.setFocus(true);
}
public void keyPressed(int code) {
int game = Display.getInstance().getGameAction(code);
if (game > 0) {
super.keyPressed(code);
} else {
search.keyPressed(code);
lastSearchInteraction = System.currentTimeMillis();
}
}
public void keyReleased(int code) {
int game = Display.getInstance().getGameAction(code);
if (game > 0) {
super.keyReleased(code);
} else {
search.keyReleased(code);
lastSearchInteraction = System.currentTimeMillis();
String t = search.getText();
int modelSize = getModel().getSize();
for(int iter = 0 ; iter < modelSize ; iter++) {
String v = getModel().getItemAt(iter).toString();
if(v.startsWith(t)) {
setSelectedIndex(iter);
return;
}
}
}
}
public void paint(Graphics g) {
super.paint(g);
if (System.currentTimeMillis() - 1000 < lastSearchInteraction || search.isPendingCommit()) {
search.setSize(search.getPreferredSize());
Style s = search.getStyle();
search.setX(getX() + getWidth() - search.getWidth() - s.getPadding(RIGHT) - s.getMargin(RIGHT));
search.setY(getScrollY() + getY());
search.paintComponent(g, true);
}
}
public boolean animate() {
boolean val = super.animate();
if(lastSearchInteraction != -1) {
search.animate();
if(System.currentTimeMillis() - 1000 > lastSearchInteraction && !search.isPendingCommit()) {
lastSearchInteraction = -1;
search.clear();
}
return true;
}
return val;
}
};
0 comments:
Post a Comment