這兩天一直在忙一個Android studio插件的事,為的是簡化android開發,是以在這裡我總結一下關于插件開發的相關知識,感興趣的開發者可以自己試一下,對于一個android開發者來說還是很有必要的。
準備
android studio的插件開發必須用IntelliJ IDEA,不能直接在android studio中直接開發,是以首先下載下傳IntelliJ IDEA。
建立新工程
選擇工程類型:
建立完畢
建立一個行為
右鍵點選src,New->Action(在偏下面的位置)
在彈出的對話框(如上圖所示)中填寫内容:
我選擇的是GenerateGroup,也就是程式中郵件菜單中的generate選項。當然你也可以添加到AS的頂部菜單中,如File,Code等等。
這時會生成一個Class:
現在我們可以做個測試,修改代碼:
@Override
public void actionPerformed(AnActionEvent e) {
System.out.printf("okokokokoko");
}複制代碼
點選運作。
這時會啟動一個IntelliJ IDEA的程式,你随便建立一個就能進去。
這時我們建立一個檔案,然後在檔案内點選右鍵,選擇Generate,會彈出如下一個菜單:
這就是我們剛剛添加進去的TESTNAME,點選,回去看下控制台發現列印了我們剛才寫的東西:
功能描述
上面介紹完了怎麼在IDE中插入一個按鈕行為,但是我們能進行什麼操作呢?下面就介紹一下。(需要将繼承的AnAction改成BaseGenerateAction)
在代碼中插入方法:
插入代碼需要一個調用一個類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[];
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()
.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();複制代碼
解析xml檔案
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>){
include = mPsiFiles[];
}
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 != ) {
return null; // not enough parts
}
return parts[];
}複制代碼
其他方法
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開頭,在開頭不能有空格,而且注意大括号不能缺失。