Search code examples
dialogcodenameoneactionevent

Codename One set action event from different class for button in dialog


I have an Android application with a dialog and a few buttons inside.

I want to reuse the dialog for different purposes and looking for a way to call the button from a separate class and define an action event for it.

Creating a test class, I managed to define an action event for a button inside a form, but the same code does not work for a button inside a dialog, and I can't get my head around why it is not working for the dialog.

Below is what I already have. Any suggestions would be appreciated.

 public Class One {

    Test test = new Test();
    test.testOne();                        // this is working : button prints
    test.testTwo();                        // this is not working : button does not print
    buttonTest = test.getTestButton();
    buttonTest.setText("Hello World");     // not working for a button in a dialog
    buttonTest.addActionListener(l-> {     // prints when the button in a Form
        System.out.println("try");         // does not print when the button is in a dialog

    });
 }

public class Test {

    Dialog dialog = new Dialog();
    Form form = new Form();
    Button button;

    public void testOne() {

        button = new Button("Test");

        form.add(button);
        form.show();

    }

    public void testTwo() {

        button = new Button("Testing");

        dialog.add(button);
        dialog.show();

    }

    public Button getTestButton () {
        return button;
    }


}

Solution

  • You add the action listener after showing the form and dialog. This isn't a problem for the form since the forms show method will continue. But a dialogs show() method will block.

    Two solutions:

    • Move the listener binding higher in the code (before the show) that would be a problem since the button doesn't exist yet so you will need some refactoring.

    • Change the show() call on the dialog to showModless()