目标
下图中”Tree View Container”处,要想加入一个图标
步骤
1. 加入图标
package.json中以下几项为必须:
{
"activationEvents": [
"onView:codeLearning",
],
"contributes": {
"viewsContainers": {
"activitybar": [
{
"id": "codeLearningExplorer",
"title": "Learning to Code",
"icon": "media/icon.svg"
}
]
},
"views": {
"codeLearningExplorer": [
{
"id": "codeLearning",
"name": "Code Learning"
}
]
}
},
}
其中的viewContainers定义了上图中的按钮,views定义了这个按钮对应的view,activationEvents表示当用户点击这个按钮时,本扩展会被唤醒,调用extension入口的activate函数,这个函数只会被调用一次。
2. 提供数据
在activate入口中,要为这个view指定data provider:
const treeProvider = new CodeLearningTreeProvider();
vscode.window.registerTreeDataProvider('codeLearning', treeProvider);
这个data provider要实现 vscode.TreeDataProvider
接口:
import * as vscode from 'vscode';
export class CodeLearningTreeProvider implements vscode.TreeDataProvider<TreeNode> {
private _onDidChangeTreeData: vscode.EventEmitter<TreeNode | undefined> = new vscode.EventEmitter<TreeNode | undefined>();
readonly onDidChangeTreeData: vscode.Event<TreeNode | undefined> = this._onDidChangeTreeData.event;
getTreeItem(element: TreeNode): vscode.TreeItem {
return element;
}
getChildren(element?: TreeNode): Thenable<TreeNode[]> {
if (element) {
console.log("getting children of " + element.label);
return Promise.resolve([])
} else {
console.log("getting children of null");
return Promise.resolve([new TreeNode("Root", vscode.TreeItemCollapsibleState.Expanded)]);
}
}
}
class TreeNode extends vscode.TreeItem {
constructor(
public readonly label: string,
public readonly collapsibleState: vscode.TreeItemCollapsibleState
) {
super(label, collapsibleState);
}
}