Getting(or setting) enabled/disabled state of a ToggleMenuItem.

Hello all,

I have a toggle menu item built with code instead of xml

var toggleMenu = new WatchUi.Menu2({:title=>"Toggles"});
toggleMenu.addItem(new WatchUi.ToggleMenuItem("item1", {:enabled=>"Right Toggle: on", :disabled=>"Right Toggle: off"}, "item1", false, {:alignment=>WatchUi.MenuItem.MENU_ITEM_LABEL_ALIGN_RIGHT}));

When I try to find the current state of the toggle menu sub label with item.getSubLabel() I see the key/value pair below the code snippet ( item.getSubLabel().equals("enabled")  does not work either)

if (item.getId().equals("item1")){
    System.println(item.getSubLabel());
    if (item.getSubLabel() == :enabled){
        System.println("item1 toggle is enabled");
    }
}

{symbol (8390438)=>Right Toggle: on, symbol (8390439)=>Right Toggle: off}

How do I get the current state of the toggle ( enabled or disabled)  ?

I also tried item.isEnabled() and it just gives me an error below:

 Cannot find symbol ':isEnabled' on type '$.Toybox.WatchUi.MenuItem'

Any thoughts or guidance is appreciated. 

Top Replies

All Replies

  •  Cannot find symbol ':isEnabled' on type '$.Toybox.WatchUi.MenuItem'

    I assume the second code snippet is part of onSelect() in a Menu2InputDelegate.

    You're getting that message (at compile-time) because the type checker doesn't know that the selected menu item is a ToggleMenuItem.

    Try this:

    function onSelect(item as WatchUi.MenuItem) as Void {
        if (item.getId().equals("item1")) {
            var toggleItem = item as WatchUi.ToggleMenuItem;
            System.println("item1: toggleItem.isEnabled() = " + toggleItem.isEnabled());
        }
    }

    Here's a more generic solution (although probably more generic than is practical or necessary in most cases - it's just to illustrate how you'd ensure that an arbitrary selected menu item is in fact a toggle menu item at runtime.)

    function onSelect(item as WatchUi.MenuItem) as Void {
        var id = item.getId() as Object or Null; // I don't think this cast should be necessary, but the type checker doesn't like line 4 otherwise
        if (item instanceof WatchUi.ToggleMenuItem) {
            System.println("item ID: " + id);
            System.println("item.isEnabled() = " + item.isEnabled());
        }
    }

    EDIT: clean up examples

  • Hi FlowState, 

    It works :). Thank you for the detailed answer and explanation, I understand it now.