Search code examples
javascriptandroidxmlblockly

Creating a custom block and writing the code to generate the Javascript code on Android


I want a different category of blocks called 'Movement' with two blocks inside it called MoveForward and MoveBackward.

In the toolbox.xml file in blockly core library, I added the XML code for creating the UI.

<category name="Movement" colour="190">

        <block type="move_forward">
            <value name="TEXT">
                <shadow type="text">
                    <field name="TEXT">4</field>
                </shadow>
            </value>
        </block>

        <block type="move_backward">
            <value name="TEXT">
                <shadow type="text">
                    <field name="TEXT">4</field>
                </shadow>
            </value>
        </block>

</category>

Now where do I need to add the JavaScript code that will create the output JavaScript code when these bocks are used and run ? In simple terms, what extra I need to do to make these blocks generate the JavaScript code ?


Solution

  • I'm assuming you've already written your block definitions and these blocks show up in the toolbox UI. In which case, the code generators are the piece you are missing. The generators defined in JavaScript on all blockly platforms. They look like this:

    // From the Android turtle demo.
    // https://github.com/google/blockly-android/blob/master/blocklydemo/src/main/assets/turtle/generators.js
    Blockly.JavaScript['turtle_move_internal'] = function(block) {
      // Generate JavaScript for moving forward or backwards.
      var value = block.getFieldValue('VALUE');
      return 'Turtle.' + block.getFieldValue('DIR') +
          '(' + value + ', \'block_id_' + block.id + '\');\n';
    };
    

    Blockly.JavaScript is an map of block type names (move_forward and move_backward, in your case) to JavaScript generator functions. Each generator function is passed in a JavaScript Block object. This is the same API used everywhere in the web version of Blockly.

    Write your own generator file. If you're using Android, this should go in your assets folder, and one of the assets paths returned by AbstractBlocklyActivity.getGeneratorsJsPaths().