Android MVP code automatic generation plug-in development

Get into the habit of writing together! This is the 12th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

While enjoying the clean code that the MVP pattern brings, we seem to have to put up with writing more code and creating more files.

But programmers with the excellent quality of laziness will always find a solution to this dilemma.

This article was written when lucio was an intern in 2017 and was engaged in Android development. Now it seems that there are still some references.

The reason why this article will appear is that lucio is developing a small program following the pattern of Google's Android MVP sample code, and found that we will need to write a lot of repeated code, and more troublesome is that we need to create a lot of repeated files. Every time you develop a small module, you will need to create at least four files: Activity, Contract, Fragment, and Presenter.

In short, while enjoying the clean code that the MVP pattern brings, we seem to have to put up with writing more code and creating more files.

But programmers with the excellent quality of laziness will always find a solution to this dilemma.

lucio started looking for a code auto-generation plugin for Android Studio, hoping for a great plugin that would solve my dilemma, but it didn't turn out well. Among the related plug-ins, many plug-ins are excellent, but the code structure it generates is not what I expected - I hope that each small module can become a package by itself, instead of dividing the whole program into several large packages, the former is not suitable for Better readability for me, and the code generated by some other plugins has many small differences from what I expected.

After reading the source code of several plug-ins, I found that it is not difficult to develop a plug-in, so lucio decided to write a plug-in by himself!

The specific implementation ideas are as follows:

  1. Define the template of the class file, read the template, modify the keyword and output the class source code
  2. Use Intellij IDEA to develop plug-ins to provide a refreshing visual interface

generate code

Realize ideas

  1. Write two txt files as templates
  2. Read the template and modify the fields that are not common in it
  3. Output the generated code to the specified file.

Template example

package &package&;

/**
 * Created by xxx on xxxx/xx/xx.
 */

public interface BaseView<T> {

    void setPresenter(T presenter);

}
复制代码
package &package&;

/**
 * Created by xxx on xxxx/xx/xx.
 */

public interface BasePresenter {

    void start();

}
复制代码

Program example

You can see that all we need to modify is the path name. We only need to read the template file and replace all &package& with the real package name. To generate the package name, you can take the path under the java folder and change "/" to ".".

/**
 * 获取包名
 */
private String getPackageName(String path) {
	return path.substring(path.indexOf("java") + 5, path.length()).replace("/", ".");
}
复制代码
/**
  * 生成BaseView.java
  */
private void genBaseView(String path) {
        File codeBaseView = new File(path + "\\base\\" + "BaseView.java");
        String strTemplateBaseView = readTemplateFile("BaseView.txt");
        String strCodeBaseView = strTemplateBaseView.replaceAll("&package&", getPackageName(path) + ".base");

        try {
            FileUtils.writeStringToFile(codeBaseView, strCodeBaseView);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
复制代码

Summarize

同样的,我们可以生成生成&ModelName&Activity.java、&ModelName&Contract.java、&ModelName&Fragment.java和&ModelName&Presenter.java,做法是相似的,我们只需要更改一些不通用的字段。

如果需要继续扩展,我们还可以让一些工具类的代码也使用自动生成的方式创建。

上面用到的路径,我们期望是点击右键时所在的包下的路径,这在用IDEA开发插件时很容易获取,下面我们看下IDEA开发Android Studio插件的过程。

IDEA开发Android Studio插件

实现过程

  1. 新建IntellJ Platform Plugin项目
  2. 新建一个Action,设置唤起插件的方式
  3. 编写插件

Create a new IntellJ Platform Plugin project

我们直接使用Messages类创建对话框,很方便可以不去考虑界面代码的编写,当然如果期望有更好的交互,也可以自己编写界面。下面我们创建了三个对话框分别完成基类、工具类和模块内类文件的自动生成。

程序示例

通过下面的代码获取右键点击位置所在的路径:

project = e.getProject();
        selectGroup = DataKeys.VIRTUAL_FILE.getData(e.getDataContext());
        String path = selectGroup.getPath();
复制代码
public class AutoGen extends AnAction {

    Project project;
    VirtualFile selectGroup;

    @Override
    public void actionPerformed(AnActionEvent e) {
        project = e.getProject();
        selectGroup = DataKeys.VIRTUAL_FILE.getData(e.getDataContext());
        String path = selectGroup.getPath();

        int resultCode = Messages.showYesNoCancelDialog(project,"New base class(BasePresenter.java and BaseView.java)",
                "New Base Class", null);
        if(resultCode==0) {
            GenMVPCode genMVPCode = new GenMVPCode();
            genMVPCode.genBaseClassCode(path);
        }

        int resultCodeUtils = Messages.showYesNoCancelDialog(project,"New utils class(ActivityUtils.java, LogUtils.java and ToastUtils.java)",
                "New Base Class", null);
        if(resultCodeUtils==0) {
            GenMVPCode genMVPCode = new GenMVPCode();
            genMVPCode.genUtilsClassCode(path);
        }

        String modelName = Messages.showInputDialog(project, "Please input model name", "New MVP Model", Messages.getQuestionIcon());
        if (modelName == null || modelName.equals("")) {
            Messages.showErrorDialog("Model name can not be empty!","Model name is empty.");
            return;
        }else{
            GenMVPCode genMVPCode = new GenMVPCode();
            genMVPCode.genModelCode(path,modelName);
        }
    }
}

复制代码

试试运行一下,我们可以在指定的路径下生成我们的代码,当然还有一些依赖库和界面文件不存在可能报错,但这已经极大地方便了我们在Android Studio中去创建一个新的模块了。存在的问题我们以后再继续改进。

directory to generate files

Generated Activity file

如果熟悉Java Swing,我们还可以开发出比较好看一点的对话框。当然这个插件还有其他许多可以改进的地方,如检测模块名称是否规范,还可以根据在对话框的输入使用Javapoet在Contract生成方法。这是一个很简单的插件,根据每个人需求不同,可以扩展出不同的用法。

发布插件

为了和更多的人分享我们的成果,我们选择在JetBrains Plugins Repository发布我们的插件。

1.填写plugin.xml的信息
<idea-plugin>
  <id>com.luciozhang.plugin.id</id>
  <name>MVPAutoGen</name>
  <version>1.0</version>
  <vendor email="[email protected]" url="http://blog.csdn.net/qq_18738333">luciozhang</vendor>

  <description><![CDATA[
      A plugin for Android Studio MVP code automatically generating.<br>
      <em>https://github.com/zxchehe/MVPAutoGen</em>
    ]]></description>

  <change-notes><![CDATA[
      No change notes here.<br>
      <em>https://github.com/zxchehe/MVPAutoGen</em>
    ]]>
  </change-notes>

  <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
  <idea-version since-build="145.0"/>

  <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
       on how to target different products -->

  <depends>com.intellij.modules.lang</depends>


  <extensions defaultExtensionNs="com.intellij">
    <!-- Add your extensions here -->
  </extensions>

  <actions>
    <!-- Add your actions here -->
    <action id="autogen" class="AutoGen" text="AutoGenMVP" description="Automatically generated MVP code">
      <add-to-group group-id="NewGroup" anchor="first"/>
    </action>
  </actions>

</idea-plugin>
复制代码

Note that uncomment the line com.intellij.modules.lang so that the plugin can be published to all platforms, otherwise it will only be published to Intellij Idea.

2. Register an account at JetBrains Plugins Repository
3. Pack

Right-click the project name -> Prepare Plugin Module 'xxxx' For Deployment will generate the jar package of the project, and if there is a third-party library, a zip package will be generated, or it can be used directly.

4. Just wait for two working days to upload the plugin on the official website

After passing the review, we can share our plugin with others in Android Studio.

Browse our plugins

Looking at the running effect, it basically meets our expectations.

generate mvp code

generate results

Guess you like

Origin juejin.im/post/7085719381384101918