這兩天一直在忙一個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[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();
解析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>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開頭,在開頭不能有空格,而且注意大括號不能缺失。