Monday, July 2, 2012

A convenient toggle handler

Toggle buttons always seemed a bit awkward to me as there seems to be no uniform interface to store the toggle state. In the past I used Ralf Eberts ToggleHandler. But reading/setting and persisting the toggle state programmatically was always painful.

Now I rediscovered a post by Prakash G.R. and built my own ToggleHandler (view online) on top of this.

Using the handler

As stated in the referenced post the command contribution needs a state definition to store the current toggle state to:
<command      ...>       
   <state       
         class="org.eclipse.ui.handlers.RegistryToggleState:true"       
         id="org.eclipse.ui.commands.toggleState">       
   </state>       
</command> 

Then your handler just needs to extend AbstractToggleHandler. The toggle state will automatically be preserved when you close your application.

You can programmatically set the state of any such toggle command by executing
ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
Command command = commandService.getCommand(commandId);
AbstractToggleHandler.setCommandState(command, true);

This will also toggle a visible button using this command.

No comments:

Post a Comment