这两天一直在忙一个Android studio插件的事,为的是简化android开发,因此在这里我总结一下关于插件开发的相关知识,感兴趣的开发者能够本身试一下,对于一个android开发者来讲仍是颇有必要的。javascript
android studio的插件开发必须用IntelliJ IDEA,不能直接在android studio中直接开发,因此首先下载IntelliJ IDEA。java
右键点击src,New->Action(在偏下面的位置)android
在弹出的对话框(如上图所示)中填写内容:app
我选择的是GenerateGroup,也就是程序中邮件菜单中的generate选项。固然你也能够添加到AS的顶部菜单中,如File,Code等等。ide
这时会生成一个Class:测试
如今咱们能够作个测试,修改代码:ui
@Override
public void actionPerformed(AnActionEvent e) {
System.out.printf("okokokokoko");
}复制代码
点击运行。
这时会启动一个IntelliJ IDEA的程序,你随便新建一个就能进去。
这时咱们新建一个文件,而后在文件内点击右键,选择Generate,会弹出以下一个菜单:this
这就是咱们刚刚添加进去的TESTNAME,点击,回去看下控制台发现打印了咱们刚才写的东西:idea
上面介绍完了怎么在IDE中插入一个按钮行为,可是咱们能进行什么操做呢?下面就介绍一下。(须要将继承的AnAction改为BaseGenerateAction)spa
插入代码须要一个调用一个类WriteCommandAction.Simple。
咱们新建一个类继承WriteCommandAction.Simple:
public class LayoutCreator extends WriteCommandAction.Simple{
private Project project;
private PsiFile file;
private PsiClass targetClass;
private PsiElementFactory factory;
public LayoutCreator(Project project, PsiClass targetClass, PsiElementFactory factory, PsiFile... files) {
super(project, files);
this.project = project;
this.file = files[0];
this.targetClass = targetClass;
this.factory = factory;
}
@Override
protected void run() throws Throwable {
}
}复制代码
咱们能够在run方法中进行插入操做。
例如咱们插入一个方法
@Override
protected void run() throws Throwable {
// 将弹出dialog的方法写在StringBuilder里
StringBuilder dialog = new StringBuilder();
dialog.append("public void showDialog(){");
dialog.append(" android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);");
dialog.append(" builder.setTitle(\"Title\")\n");
dialog.append(".setMessage(\"Dialog content\")\n");
dialog.append(".setPositiveButton(\"OK\", new android.content.DialogInterface.OnClickListener() {\n" +
"@Override\n" +
"public void onClick(DialogInterface dialog, int which) {\n" +
"\t\n" +
"}" +
"})\n");
dialog.append(".setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n" +
"@Override\n" +
"public void onClick(DialogInterface dialog, int which) {\n" +
"\t\n" +
"}" +
"})\n");
dialog.append(".show();");
dialog.append("}");
targetClass.add(factory.createMethodFromText(dialog.toString(), targetClass));
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
styleManager.optimizeImports(file);
styleManager.shortenClassReferences(targetClass);
}复制代码
而后再看一下这个方法怎么调用:
@Override
public void actionPerformed(AnActionEvent e) {
Project project = e.getData(PlatformDataKeys.PROJECT);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
PsiClass targetClass = getTargetClass(editor, file);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
new LayoutCreator(project, targetClass, factory, file).execute();
}复制代码
这样就能够插入一个方法。
咱们也能够在IDE中弹出一个错误提示:
public static void showNotification(Project project, MessageType type, String text) {
StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, type, null)
.setFadeoutTime(7500)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.getComponent()), Balloon.Position.atRight);
}复制代码
public static void findFile(Project project,String name){
PsiFile[] mPsiFiles = FilenameIndex.getFilesByName(project,name, GlobalSearchScope.allScope(project));
System.out.printf("length="+mPsiFiles.length);
}复制代码
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if (null == editor) {
return;
}
SelectionModel model = editor.getSelectionModel();
//获取选中内容
final String selectedText = model.getSelectedText();复制代码
public static ArrayList<Element> getIDsFromLayout(final PsiFile file, final ArrayList<Element> elements) {
file.accept(new XmlRecursiveElementVisitor() {
@Override
public void visitElement(final PsiElement element) {
super.visitElement(element);
//解析XML标签
if (element instanceof XmlTag) {
XmlTag tag = (XmlTag) element;
//解析include标签
if (tag.getName().equalsIgnoreCase("include")) {
XmlAttribute layout = tag.getAttribute("layout", null);
if (layout != null) {
Project project = file.getProject();
// PsiFile include = findLayoutResource(file, project, getLayoutName(layout.getValue()));
PsiFile include = null;
PsiFile[] mPsiFiles = FilenameIndex.getFilesByName(project, getLayoutName(layout.getValue())+".xml", GlobalSearchScope.allScope(project));
if (mPsiFiles.length>0){
include = mPsiFiles[0];
}
if (include != null) {
getIDsFromLayout(include, elements);
return;
}
}
}
// get element ID
XmlAttribute id = tag.getAttribute("android:id", null);
if (id == null) {
return; // missing android:id attribute
}
String value = id.getValue();
if (value == null) {
return; // empty value
}
// check if there is defined custom class
String name = tag.getName();
XmlAttribute clazz = tag.getAttribute("class", null);
if (clazz != null) {
name = clazz.getValue();
}
try {
Element e = new Element(name, value, tag);
elements.add(e);
} catch (IllegalArgumentException e) {
// TODO log
}
}
}
});
return elements;
}
public static String getLayoutName(String layout) {
if (layout == null || !layout.startsWith("@") || !layout.contains("/")) {
return null; // it's not layout identifier
}
String[] parts = layout.split("/");
if (parts.length != 2) {
return null; // not enough parts
}
return parts[1];
}复制代码
FilenameIndex.getFilesByName() //经过给定名称(不包含具体路径)搜索对应文件
ReferencesSearch.search() //相似于IDE中的Find Usages操做
RefactoringFactory.createRename() //重命名
FileContentUtil.reparseFiles() //经过VirtualFile重建PSI
ClassInheritorsSearch.search() //搜索一个类的全部子类
JavaPsiFacade.findClass() //经过类名查找类
PsiShortNamesCache.getInstance().getClassesByName() //经过一个短名称(例如LogUtil)查找类
PsiClass.getSuperClass() //查找一个类的直接父类
JavaPsiFacade.getInstance().findPackage() //获取Java类所在的Package
OverridingMethodsSearch.search() //查找被特定方法重写的方法复制代码
工程开发完毕,能够点击Build->Prepare plugin Module 'xxx' For Deployment,以后便会在工程下生成对应的xxx.jar
打开你的Android Studio,选择Preferences,如图所示:
如上图所示,选择Plugins,选择上图指示的按钮,在选择你刚才生成的jar便可。
基本上本文提到的方法能够实现基本的操做,熟练掌握插件的开发,能够加快Android开发的速度。
这里说一下我在开发中遇到的问题
添加了Action可是调试的时候发现,找不到新建的Action,多是因为你的IntelliJ IDEA版本太高,能够在plugin.xml中,找到idea-version标签,将版本改到141.0或如下便可。
插入一个方法,可是运行报错,提示不正确的方法,这是因为你在使用上文提到的插入方法时,插入的要是一个完整的方法以public 或private或protected开头,在开头不能有空格,并且注意大括号不能缺失。