目标

下图中”Tree View Container”处,要想加入一个图标

Tree View Container Extension - 图1

步骤

1. 加入图标

package.json中以下几项为必须:

  1. {
  2. "activationEvents": [
  3. "onView:codeLearning",
  4. ],
  5. "contributes": {
  6. "viewsContainers": {
  7. "activitybar": [
  8. {
  9. "id": "codeLearningExplorer",
  10. "title": "Learning to Code",
  11. "icon": "media/icon.svg"
  12. }
  13. ]
  14. },
  15. "views": {
  16. "codeLearningExplorer": [
  17. {
  18. "id": "codeLearning",
  19. "name": "Code Learning"
  20. }
  21. ]
  22. }
  23. },
  24. }

其中的viewContainers定义了上图中的按钮,views定义了这个按钮对应的view,activationEvents表示当用户点击这个按钮时,本扩展会被唤醒,调用extension入口的activate函数,这个函数只会被调用一次。

2. 提供数据

在activate入口中,要为这个view指定data provider:

  1. const treeProvider = new CodeLearningTreeProvider();
  2. vscode.window.registerTreeDataProvider('codeLearning', treeProvider);

这个data provider要实现 vscode.TreeDataProvider 接口:

  1. import * as vscode from 'vscode';
  2. export class CodeLearningTreeProvider implements vscode.TreeDataProvider<TreeNode> {
  3. private _onDidChangeTreeData: vscode.EventEmitter<TreeNode | undefined> = new vscode.EventEmitter<TreeNode | undefined>();
  4. readonly onDidChangeTreeData: vscode.Event<TreeNode | undefined> = this._onDidChangeTreeData.event;
  5. getTreeItem(element: TreeNode): vscode.TreeItem {
  6. return element;
  7. }
  8. getChildren(element?: TreeNode): Thenable<TreeNode[]> {
  9. if (element) {
  10. console.log("getting children of " + element.label);
  11. return Promise.resolve([])
  12. } else {
  13. console.log("getting children of null");
  14. return Promise.resolve([new TreeNode("Root", vscode.TreeItemCollapsibleState.Expanded)]);
  15. }
  16. }
  17. }
  18. class TreeNode extends vscode.TreeItem {
  19. constructor(
  20. public readonly label: string,
  21. public readonly collapsibleState: vscode.TreeItemCollapsibleState
  22. ) {
  23. super(label, collapsibleState);
  24. }
  25. }

3. 响应事件