Fork us on GitHub

Toolbar Search Mode

Searching using the Toolbar made easy
Post Image

Toolbar Search Mode

The Toolbar is a pretty flexible API for handling the title area. It allows a lot of things including search but up until now that very common use case was not a standard part of the API.

It is now, we just added a new API that effectively allows you to bind search to a form and just get the text searched as part of the callback. The Toolbar handles everything else including replacing the title area and returning it back to its original state when you are done.

You can also customize the appearance of the search bar by using the UIID’s: ToolbarSearch, TextFieldSearch & TextHintSearch.

In the sample below we fetch all the contacts from the device and enable search thru them, notice it expects and image called duke.png which is really just the default Codename One icon renamed and placed in the src folder:

Image duke = null;
try {
    duke = Image.createImage("/duke.png");
} catch(IOException err) {
int fiveMM = Display.getInstance().convertToPixels(5);
final Image finalDuke = duke.scaledWidth(fiveMM);
Form hi = new Form("Search", BoxLayout.y());
hi.add(new InfiniteProgress());
Display.getInstance().scheduleBackgroundTask(()-> {
    // this will take a while...
    Contact[] cnts = Display.getInstance().getAllContacts(true, true, true, true, false, false);
    Display.getInstance().callSerially(() -> {
        for(Contact c : cnts) {
            MultiButton m = new MultiButton();
            Image pic = c.getPhoto();
            if(pic != null) {
                m.setIcon(fill(pic, finalDuke.getWidth(), finalDuke.getHeight()));
            } else {

hi.getToolbar().addSearchCommand(e -> {
    String text = (String)e.getSource();
    if(text == null || text.length() == 0) {
        // clear search
        for(Component cmp : hi.getContentPane()) {
    } else {
        text = text.toLowerCase();
        for(Component cmp : hi.getContentPane()) {
            MultiButton mb = (MultiButton)cmp;
            String line1 = mb.getTextLine1();
            String line2 = mb.getTextLine2();
            boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
                    line2 != null && line2.toLowerCase().indexOf(text) > -1;
}, 4);;

Up Next

I think this shows some of the directions we will be taking with Codename One components as we move forward. Future components from us will make more use of the icon fonts and material design icons to allow a default look that "just works" everywhere.

You would still be able to customize everything like you always did but unlike the past, we hope the default look will start off as both functional and attractive.

Share this Post:

Posted by Shai Almog

Shai is the co-founder of Codename One. He's been a professional programmer for over 25 years. During that time he has worked with dozens of companies including Sun Microsystems.
For more follow Shai on Twitter & github.