本文由 Luzhuo 编写,转发请保留该信息.
原文: https://blog.csdn.net/Rozol/article/details/81947949
IntelliJ IDEA 自动编码利器
环境: Windows10 / AndroidStudio3.1
参考资源: https://www.jetbrains.com/help/idea/working-with-source-code.html
C:\Users\LZLuz\.AndroidStudio3.1\config\templates
$END$
: 最后都编辑完后光标所处的位置$SELECTION$
: 设置环绕实时代码模板 (就是模板包围代码)groovyScript("_1.take(Math.min(23, _1.length()));", className())
import * as $ITEM$ from ""$MODULE$""
or import $ITEM$ from ""$MODULE$""
based on the file name.plugin.xml配置:
lluzhuo.me.unique.plugin.id
TextPlugin
1.0
Luzhuo
most HTML tags may be used
]]>
most HTML tags may be used
]]>
com.intellij.modules.lang
常用代码演示:
package me.luzhuo;
import com.intellij.codeInsight.actions.ReformatCodeProcessor;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.EverythingGlobalScope;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.ui.JBColor;
import java.awt.*;
public class TestAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
// TODO: insert action logic here
// 1.动作出发之后执行
// 拿到当前工程对象
Project project = e.getData(PlatformDataKeys.PROJECT);
// --- 对话框 ---
String name = Messages.showInputDialog(project, "请输入内容", "标题", Messages.getQuestionIcon());
Messages.showMessageDialog(project, "提示框", "标题", Messages.getInformationIcon());
// --- 获取用户选择的文本 ---
Editor editor = e.getData(PlatformDataKeys.EDITOR); // 获取编辑器对象
SelectionModel model = editor.getSelectionModel(); // 获取用户选择对象模型
String selectText = model.getSelectedText(); // 获取模型中的文本
// --- 网络请求 ---
// 可以直接使用第三方包
// --- 线程 ---
new Thread(new Runnable() {
@Override
public void run() {
// 在子线程中不能更新ui
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
// 这里是渲染线程, 可以更新UI
}
});
}
}).start();
// --- 弹窗气泡 ---
JBPopupFactory factory = JBPopupFactory.getInstance(); // 获取默认popup工厂
BalloonBuilder builder = factory.createHtmlTextBalloonBuilder("内容", null, new JBColor(new Color(255, 255, 255), new Color(0, 0, 0)), null);// 颜色: 亮主题 / 暗主题
builder.setFadeoutTime(5000) // 无操作停留时间
.createBalloon() // 创建气泡
.show(factory.guessBestPopupLocation(editor), Balloon.Position.below); // 显示位置
// --- 文件/文件夹 ---
// 检索文件
PsiFile[] psiFiles = FilenameIndex.getFilesByName(project, "plugin" + ".xml", GlobalSearchScope.allScope(project)); // 从整个项目搜索 plugin.xml 文件
if (psiFiles.length <= 0) return;
XmlFile xmlFile = (XmlFile) psiFiles[0];
// 检索元素
xmlFile.accept(new XmlRecursiveElementVisitor(){ // 遍历元素
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
if (element instanceof XmlTag) {
XmlTag tag = (XmlTag) element;
String name = tag.getName(); // tag name
if (name.equalsIgnoreCase("include")) {
XmlAttribute layout = tag.getAttribute("layout", null);
PsiFile[] psiFiles = FilenameIndex.getFilesByName(project, layout.getValue() + ".xml", GlobalSearchScope.allScope(project)); // 搜索指定文件
XmlFile include = (XmlFile) psiFiles[0];
XmlAttribute id = tag.getAttribute("android:id", null); // 获取id字段属性
String idValue = id.getValue(); // 获取字段id值
}
}
}
});
// 获取目标Class文件
int offset = editor.getCaretModel().getOffset(); // 光标位置
PsiElement element = xmlFile.findElementAt(offset); // 对应文件
PsiClass clazz = PsiTreeUtil.getParentOfType(element, PsiClass.class);
clazz = clazz instanceof SyntheticElement ? null : clazz;
// 根据类名查找类
PsiClass activityClass = JavaPsiFacade.getInstance(project).findClass("android.app.Activity", new EverythingGlobalScope(project));
if (clazz.isInheritor(activityClass, true)){ } // 判断获取的类是否继承了 android.app.Activity
// 根据方法名查找方法
PsiMethod[] methods = clazz.findMethodsByName("onCreate", false);
PsiElementFactory factoryE = JavaPsiFacade.getElementFactory(project); // Java元素工厂
// 获取Class元素
String className = clazz.getName(); // 获取类名
PsiField[] fields = clazz.getFields(); // 获取字段
String fieldName = fields[0].getName(); // 字段名
// 添加到class
String fromText = "插入的内容";
clazz.add(factoryE.createFieldFromText(fromText, clazz)); // 插入内容到类上方
clazz.add(factoryE.createMethodFromText(fromText, clazz)); // 插入内容到类里面
// 代码块
PsiCodeBlock methodBody = methods[0].getBody();
methodBody.add(factoryE.createStatementFromText("内容", methods[0])); // 往 methods[0] 方法里的 methodBody(如: initView()) 代码块里写入 内容
// 检索方法内代码
for (PsiStatement psiStatement : methods[0].getBody().getStatements()) {
// 方法调用的代码
if (psiStatement.getFirstChild() instanceof PsiMethodCallExpression) { // psiStatement.getFirstChild() 获取第一个孩子
// 查找setContentView
PsiReferenceExpression methodExpression = ((PsiMethodCallExpression) psiStatement.getFirstChild()).getMethodExpression();
String methodCode = methodExpression.getText(); // 如方法内写了 "setContentView" 代码
// 写入 代码 到某元素 之前/后
methods[0].getBody().addAfter(factoryE.createStatementFromText("内容", clazz), psiStatement); // 将 内容 写入到 psiStatement 之后
}
// 方法return的代码
if (psiStatement instanceof PsiReturnStatement) {
PsiReturnStatement returnStatement = (PsiReturnStatement) psiStatement;
String returnValue = returnStatement.getReturnValue().getText(); // return的值
}
}
// 写入Java文件 (异步执行)
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
styleManager.optimizeImports(psiFiles[0]); // 选择文件
styleManager.shortenClassReferences(clazz); // 选择类
new ReformatCodeProcessor(project, clazz.getContainingFile(), null, false).runWithoutProgress();
}
}
Select Template
: Ctrl+Alt+J步骤:
1.在项目下创建 luzhuo.gradle
文件
ext {
android = [
compileSdkVersion: 26, // 24:7, 25:7.1.1, 26:8.0
minSdkVersion : 14,
targetSdkVersion : 26,
versionCode : 1,
versionName : "1.0"
]
// 包版本管理
dependVersion = [
support: "26.1.0"
]
dependencies = [
// ------------- Android -------------
supportV4: "com.android.support:support-v4:${dependVersion.support}", // 无须依赖
appcompatV7: "com.android.support:appcompat-v7:${dependVersion.support}", // 必须依赖
design: "com.android.support:design:${dependVersion.support}",
// --- 测试 ---
junit: "junit:junit:4.12",
espresso: "com.android.support.test.espresso:espresso-core:3.0.2",
runner: "com.android.support.test:runner:1.0.2",
// ------------- ButterKnife -------------
butterknife: 'com.jakewharton:butterknife:8.2.1',
butterknifeCompiler: 'com.jakewharton:butterknife-compiler:8.2.1',
]
}
2.使用:
apply from: "luzhuo.gradle"
改造app的build.gradle文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
defaultConfig {
applicationId "me.luzhuo.livetemplates"
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation rootProject.ext.dependencies.appcompatV7
implementation rootProject.ext.dependencies.constraint
testImplementation rootProject.ext.dependencies.junit
androidTestImplementation rootProject.ext.dependencies.runner
androidTestImplementation rootProject.ext.dependencies.espresso
implementation rootProject.ext.dependencies.butterknife
annotationProcessor rootProject.ext.dependencies.butterknifeCompiler
}