在使用Android Studio的过程中,发现自带的一些插件无法满足项目的实际需要,便着手自己开发对应的插件。下面是我开发插件过程中的一个记录,会持续和大家分享。
分享一:创建Project右键菜单
1,按照项目向导一步一步创建一个Demo项目,就不再介绍了,可以参照这篇文章http://blog.csdn.net/dc_726/article/details/14139155
2,创建Action,在plugin配置文件中你会看到
<action id="FirstAction" class="FirstAction" text="FirstAction" description="右键Action">
<add-to-group group-id="ProjectViewPopupMenu" anchor="after" relative-to-action="ReplaceInPath"/>
</action>
3,运行后,IDE会另外开启一个IDE(由一个类似Genymotion的容器包裹)。看效果是不是很熟悉,对,这就是常用Project右键菜单:
4,根据触发的文件类型动态控制Action的隐藏显示
@Override
public void update(AnActionEvent event) {//根据扩展名是否是jar,显示隐藏此Action
String extension = getFileExtension(event.getDataContext());
this.getTemplatePresentation().setEnabled(extension != null && "jar".equals(extension));
}
完整代码:
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
/**
* Created by ABC on 16/8/17.
*/
public class FirstAction extends AnAction {
private Project mProject;
@Override
public void actionPerformed(AnActionEvent event) {
mProject = event.getData(PlatformDataKeys.PROJECT);
DataContext dataContext = event.getDataContext();
if ("jar".equals(getFileExtension(dataContext))) {//根据扩展名判定是否进行下面的处理
//获取选中的文件
VirtualFile file = DataKeys.VIRTUAL_FILE.getData(event.getDataContext());
if (file != null) {
Messages.showMessageDialog(mProject, file.getName(), "select file", Messages.getInformationIcon());
}
}
}
@Override
public void update(AnActionEvent event) {
//在Action显示之前,根据选中文件扩展名判定是否显示此Action
String extension = getFileExtension(event.getDataContext());
this.getTemplatePresentation().setEnabled(extension != null && "jar".equals(extension));
}
public static String getFileExtension(DataContext dataContext) {
VirtualFile file = DataKeys.VIRTUAL_FILE.getData(dataContext);
return file == null ? null : file.getExtension();
}
}