友情提示:380元/半年,儿童学编程,就上码丁实验室。
在安卓中集成Blockly,我们可以实现如下图所示类似的可拖拽模块化/可视化编程,并可以自动生成JavaScript代码
集成方式:
1.将Github中的Blocklylib-core和blocklylib-vertical添加到我们项目的依赖中
2.创建Activity继承AbstractBlocklyActivity并实现至少以下四个方法:
getBlockDefinitionsJsonPaths() 用于获取定义块数据的json文件的路径,返回值是文件在资产目录中的路径集合。例如下代码是导入Blockly库提供的默认块,也可以自己创建:
-
-
protected List<String> getBlockDefinitionsJsonPaths() {
-
List<String> assetPaths = new ArrayList<>(DefaultBlocks.getAllBlockDefinitions());
-
// 在此添加我们自己在资产目录创建的块.
-
return assetPaths;
-
}
getToolboxContentsXmlPath() 用于获取工具箱toolbox数据的xml文件路径,返回值是文件在资产目录中的路径。例加载默认toolbox.xml:
-
-
protected String getToolboxContentsXmlPath() {
-
return “default/toolbox.xml”;
-
}
getGeneratorsJsPaths() 用于获取块生成代码的生成器js文件路径,返回值是文件在资产目录中的路径集合。
-
private static final List<String> JAVASCRIPT_GENERATORS = Arrays.asList(
-
// 添加自己定义的生成器,默认块的生成器已经包含不需要我们填写
-
);
-
-
protected List<String> getGeneratorsJsPaths() {
-
return JAVASCRIPT_GENERATORS;
-
}
getCodeGenerationCallback() 用于当运行/播放按钮被点击,代码生成后的回调,返回值是回调对象CodeGenerationRequest.CodeGeneratorCallback(),在其重写方法onFinishCodeGeneration中对代码进行需要的操作。如:
-
private final CodeGenerationRequest.CodeGeneratorCallback mCodeGeneratorCallback =
-
new CodeGenerationRequest.CodeGeneratorCallback() {
-
-
public void onFinishCodeGeneration(final String generatedCode) {
-
Toast.makeText(MainActivity.this, generatedCode, Toast.LENGTH_LONG).show();
-
Log.e(TAG, “generatedCode:\n” + generatedCode);
-
}
-
};
-
-
-
protected CodeGenerationRequest.CodeGeneratorCallback getCodeGenerationCallback() {
-
return mCodeGeneratorCallback;
-
}
简单举例的完整Activity代码:
-
public class MainActivity extends AbstractBlocklyActivity {
-
private static final String TAG = “MainActivity”;
-
private static final List<String> JAVASCRIPT_GENERATORS = Arrays.asList(new String[]{
-
“generators.js”
-
});
-
private final CodeGenerationRequest.CodeGeneratorCallback mCodeGeneratorCallback =
-
new CodeGenerationRequest.CodeGeneratorCallback() {
-
-
public void onFinishCodeGeneration(final String generatedCode) {
-
Toast.makeText(MainActivity.this, generatedCode, Toast.LENGTH_LONG).show();
-
Log.e(TAG, “generatedCode:\n” + generatedCode);
-
}
-
};
-
-
-
protected List<String> getBlockDefinitionsJsonPaths() {
-
List<String> assetPaths = new ArrayList<>(DefaultBlocks.getAllBlockDefinitions());
-
// 在此添加我们自己在资产目录创建的块.
-
return assetPaths;
-
}
-
-
-
protected String getToolboxContentsXmlPath() {
-
return “default/toolbox.xml”;
-
}
-
-
-
protected List<String> getGeneratorsJsPaths() {
-
return JAVASCRIPT_GENERATORS;
-
}
-
-
-
protected CodeGenerationRequest.CodeGeneratorCallback getCodeGenerationCallback() {
-
return mCodeGeneratorCallback;
-
}
-
}
3.在清单文件中,在该Activity的节点中增加如下属性:
android:windowSoftInputMode="stateHidden|adjustPan"
如果需要横屏显示,还可添加横屏属性:
android:screenOrientation="landscape"
4.更改values/styles.xml中AppTheme的父类Style为 BlocklyVerticalTheme
-
<style name=“AppTheme” parent=“BlocklyVerticalTheme”>
-
<!– Customize your theme here. –>
-
…
-
</style>
运行后如下图所示: