Blackberry: select item in a list, return to previous screen

后端 未结 1 1433
南旧
南旧 2021-01-16 17:47

I have prepared a very short test case (s. below) for my question.

On a button click I would like to display a list of strings in a new screen.

After the us

相关标签:
1条回答
  • 2021-01-16 18:23

    Use a callback pattern:

    class TitleScreen extends MainScreen {
    
        private ButtonField myButton;
    
        public TitleScreen() {
            super();
            setTitle("Click the button:");
    
            // TODO change the label of this button (see below)
            myButton = new ButtonField("Show the list", ButtonField.CONSUME_CLICK);
            myButton.setChangeListener(new FieldChangeListener() {
                public void fieldChanged(Field field, int context) {
                    OnItemSelectedCallback callback = 
                            new OnItemSelectedCallback() {
                        public void onItemSelected(String label) {
                             TitleScreen.this.onItemSelected(label);
                        }
                    };
                    MyScreen myScreen = new MyScreen(callback);
                    UiApplication.getUiApplication().pushScreen(myScreen);
                }
            });
            add(myButton);
        }
    
        private void onItemSelected(String label) {
            // this will be called when a menu item is executed on the MyScreen
            // e.g. you can call smth like: myButton.setLabel(label);
        }
    }
    
    interface OnItemSelectedCallback {
        void onItemSelected(String label);
    }
    
    class MyScreen extends MainScreen {
        ObjectListField myList = new ObjectListField();
    
        private final OnItemSelectedCallback onItemSelectedCallback;
    
        public MyScreen(OnItemSelectedCallback onItemSelectedCallback) {
            setTitle("Select an item below:");
    
            this.onItemSelectedCallback = onItemSelectedCallback;
    
            myList.set(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", }); 
            add(myList);
    
            addMenuItem(myMenu);
        }
    
        private final MenuItem myMenu = new MenuItem("Select item", 0, 0) {
            public void run() { 
                int index = myList.getSelectedIndex();
                if (index < 0)
                    return;
    
                String item = (String) myList.get(myList, index);
                Status.show("Selected: " + item);
    
                // TODO how to return to the previous screen here?
                // TODO how to call myButton.setLabel(item) here?
    
                // notify the parent screen
                onItemSelectedCallback.onItemSelected(item);
    
                // close the current screen
                UiApplication.getUiApplication().popScreen(MyScreen.this);
            }
        };
    }
    
    0 讨论(0)
提交回复
热议问题