Add Custom Blocks

Blocks are composed of three components:

  • Block definition object: Defines the look and behavior of a block, including the text, color, fields, and connections.
  • Toolbox reference: A reference to the block type in the toolbox XML, so users can add it to the workspace.
  • Generator function: Generates the code string for this block. It is always written in JavaScript, even if the target language is not JavaScript.

While the web version of Blockly also supports building block definition objects programmatically in JavaScript, this is unsupported by Blockly for Android.

Block Definition

The easiest way to build new block definitions is to use the Blockly Developer Tools. Since Blockly for Android only supports JSON formatted block definitions, set the factory's "Language Code" to JSON. Details on this format can be found here.

When using the AbstractBlocklyActivity, the block definition files are provided by getBlockDefinitionsJsonPaths(), which returns a list of application asset paths. The block definitions can be reloaded by calling reloadBlockDefinitions().

When using the raw BlocklyController, add block definitions via one of the BlocklyController.addBlockDefinitions(..) methods.

Multiple .json files can be loaded, though you should be sure the block type IDs are unique.

Add Toolbox Reference

Once the system knows about your new blocks, you need to let your users know, too. The toolbox shows users what blocks are available to them. Blockly uses the same XML toolbox definition file as Blockly on the web, detailed here.

AbstractBlocklyActivity populates the Toolbox with the contents of the .xml asset file provided by getToolboxContentsXmlPath(), and reloadToolbox() will reload the toolbox (calling getToolboxContentsXmlPath() again).

You can also call any of the BlocklyController.setToolboxConfiguration(..) methods.

In general, most blocks should be included in the toolbox, but some can be left out. This can be used to support deprecated blocks, teach individual concepts, or to hide blocks that currently can't be used. See Populate the Toolbox for more details.

Add Generator Function

Finally, to transform the block into code, pair the block type with a JavaScript generator function.

See Use Custom Generators for more details.