AndroidStudio4.1 自定义模板

原创文件,禁止未授权转载

AndroidStudio4.0之前,可以在template的文件夹里使用freemarker的自定义模板,可以在AndroidStudio的文件夹中,随意的添加适合自己的自定义模板,之前鸿洋大神的文章已经有来详细的介绍(https://blog.csdn.net/lmj623565791/article/details/51592043)。
但是从4.1版本开始提供新的方式,Geminio,用Kotlin的形式编写新的template,而且需要使用插件的形式,才能使用自定义的模板,摸索了好几天,终于解决了。

我的项目是使用MVVM的开发框架,每次在编写一个新的页面的时候,就需要新建四个文件Activity/Fragment, ViewModel, Repository, xml文件,写的多了就会很烦。自从使用了自定义的模板以后,头发掉得都少了。

开工!!!搞起!!!

#准备

开发工具 AndroidStudio4.1

模板基础代码配置

打开https://github.com/JetBrains/intellij-platform-plugin-template,点击绿色的#Use this template#,按步骤在自己的github上创建模板。
然后使用AndroidStudio 将模板下载到本地。

编码

添加wizard-template.jar

在根目录里添加lib文件夹,并添加AndroidStudio安装目录里的wizard-template.jar,位于 /Applications/Android\ Studio.app/Contents/plugins/android/lib/目录下。

修改build.gradle.kts

在dependencies里添加wizard-template.jar的依赖

1
2
3
4
dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.15.0")
compileOnly(files("lib/wizard-template.jar"))
}

修改gradle.properties

修改gradle.properties中的pluginGroup, pluginName_, platformPlugins, platformVersion。

1
2
3
4
pluginGroup = com.bigaddemo.mvvm
pluginName_ = bigaddemo_MVVM
platformVersion = 2020.2
platformPlugins = java, com.intellij.java, org.jetbrains.android, android, org.jetbrains.kotlin

将默认的listeners的父包名,调整为自己想要的样子,例如com.company.app

修改MyProjectManagerListener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
internal class MyProjectManagerListener : ProjectManagerListener {

override fun projectOpened(project: Project) {
projectInstance = project
project.getService(MyProjectService::class.java)
}

override fun projectClosing(project: Project) {
projectInstance = null
super.projectClosing(project)
}

companion object {
var projectInstance: Project? = null
}
}

在src/main/kotlin里创建other文件夹用于放置自定义模板

正式开始编写自定义模板,以Activity为例。

1. 实现WizardTemplateProvider

SamplePluginTemplateProviderImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package other
import com.android.tools.idea.wizard.template.Template
import com.android.tools.idea.wizard.template.WizardTemplateProvider
import other.mvvm.activity.mvvmActivityTemplate
import other.mvvm.fragment.mvvmFragmentTemplate
class SamplePluginTemplateProviderImpl : WizardTemplateProvider() {

override fun getTemplates(): List<Template> = listOf(
// activity的模板
mvvmActivityTemplate,
// fragment的模板
mvvmFragmentTemplate
)
}

2. 创建 mvvmActivityTemplate.kt.

这个文件是设置在创建Activity的时候,输入的信息,例如ActivityName,layoutName,packageName以及是否可以为为等
mvvmActivityTemplate.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package other.mvvm.activity

import com.android.tools.idea.wizard.template.*
import com.android.tools.idea.wizard.template.impl.activities.common.MIN_API


val mvvmActivityTemplate
get() = template {
revision = 1
name = "MVVM Activity"
description = "适用于BigaDemoMVVM框架的Activity"
minApi = MIN_API
minBuildApi = MIN_API

category = Category.Other
formFactor = FormFactor.Mobile
screens = listOf(WizardUiContext.ActivityGallery, WizardUiContext.MenuEntry, WizardUiContext.NewProject, WizardUiContext.NewModule)

lateinit var layoutName: StringParameter

val activityClass = stringParameter {
name = "Activity Name"
default = "Main"
help = "只输入名字,不要包含Activity"
constraints = listOf(Constraint.NONEMPTY)
}

layoutName = stringParameter {
name = "Layout Name"
default = "activity_main"
help = "请输入布局的名字"
constraints = listOf(Constraint.LAYOUT, Constraint.UNIQUE, Constraint.NONEMPTY)
suggest = { "${activityToLayout(activityClass.value.toLowerCase())}" }
}

val packageName = defaultPackageNameParameter

widgets(
TextFieldWidget(activityClass),
TextFieldWidget(layoutName),
PackageNameWidget(packageName)
)
// thumb { File("logo.png") }
recipe = { data: TemplateData ->
mvvmActivityRecipe(
data as ModuleTemplateData,
activityClass.value,
layoutName.value,
packageName.value)
}
}


val defaultPackageNameParameter
get() = stringParameter {
name = "Package name"
visible = { !isNewModule }
default = "com.mycompany.myapp"
constraints = listOf(Constraint.PACKAGE)
suggest = { packageName }
}

3. 创建mvvmActivityRecipe.kt。

这个文件用于将创建的文件保存到文件夹中,例如Activity,布局文件等。原计划将Activity直接添加到AndroidManifest里,但是发现generateManifest有点问题,导致生成的插件不能使用,暂时去掉,只能手动添加了。

mvvmActivityRecipe.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package other.mvvm.activity

import com.android.tools.idea.wizard.template.ModuleTemplateData
import com.android.tools.idea.wizard.template.RecipeExecutor
import other.mvvm.activity.res.layout.mvvmActivityXml
import other.mvvm.activity.src.app_package.mvvmAcitivityKt
import other.mvvm.activity.src.app_package.mvvmRepository
import other.mvvm.activity.src.app_package.mvvmViewModel


fun RecipeExecutor.mvvmActivityRecipe(
moduleData: ModuleTemplateData,
activityClass: String,
layoutName: String,
packageName: String
) {
val (projectData, srcOut, resOut) = moduleData
val ktOrJavaExt = projectData.language.extension
// generateManifest(
// moduleData = moduleData,
// activityClass = "${activityClass}Activity",
// activityTitle = activityClass,
// packageName = packageName,
// isLauncher = false,
// hasNoActionBar = false,
// generateActivityTitle = true,
// requireTheme = false,
// useMaterial2 = false
// )

val mvvmActivity = mvvmAcitivityKt(projectData.applicationPackage, activityClass, layoutName, packageName)
// 保存Activity
save(mvvmActivity, srcOut.resolve("${activityClass}Activity.${ktOrJavaExt}"))
// 保存xml
save(mvvmActivityXml(packageName, activityClass), resOut.resolve("layout/${layoutName}.xml"))
// 保存viewmodel
save(mvvmViewModel(packageName, activityClass), srcOut.resolve("${activityClass}ViewModel.${ktOrJavaExt}"))
// 保存repository
save(mvvmRepository(packageName, activityClass), srcOut.resolve("${activityClass}Repository.${ktOrJavaExt}"))
}

4. 创建mvvmAcitivityKt。

这个文件用于创建Activity的模板代码,根据自己的情况,自行调整。

mvvmAcitivityKt.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package other.mvvm.activity.src.app_package

fun mvvmAcitivityKt(
applicationPackage:String?,
activityClass:String,
layoutName:String,
packageName:String
)="""
package ${packageName}
import android.os.Bundle
import com.bigademo.baselib.base.BaseActivity
import ${applicationPackage}.R
import ${applicationPackage}.BR;
import ${applicationPackage}.databinding.Activity${activityClass}Binding
class ${activityClass}Activity : BaseActivity<${activityClass}ViewModel, Activity${activityClass}Binding>() {
override fun getContentView(): Int {
return R.layout.${layoutName}
}

override fun init(savedInstanceState: Bundle?) {
super.init(savedInstanceState)
isShowTopBar = false
}

override fun initViewModel() {
viewModel = ${activityClass}ViewModel()
}
/**
* 监听数据的变化
*/
override fun observe() {

}

/**
* 控件的点击事件
*/
override fun onClick() {
}

override fun initData() {
super.initData()
}
override fun initVariableId(): Int {
TODO("Not yet implemented")
}
}
"""

5. 编写mvvmRepository。

这个文件是mvvm的repository层的代码。

mvvmRepository.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package other.mvvm.activity.src.app_package


fun mvvmRepository(
packageName:String,
activityClass:String
)="""
package ${packageName}

import androidx.lifecycle.MutableLiveData
import com.shide.baselib.base.basemvvm.BaseRepository
import com.shide.baselib.base.basemvvm.BaseViewModel
import com.shide.baselib.net.exception.ShideApiException
import kotlinx.coroutines.CoroutineScope

class ${activityClass}Repository(
baseViewModel: BaseViewModel,
coroutineScope: CoroutineScope,
errorLiveData: MutableLiveData<ShideApiException>
) : BaseRepository(baseViewModel, coroutineScope, errorLiveData) {
}
"""

6. 编写mvvmViewModel。这个是mvvm的viewmodel层

mvvmViewModel.kt

1
2
3
4
5
6
7
8
9
10
11
12
package other.mvvm.activity.src.app_package
fun mvvmViewModel(
packageName:String,
activityClass:String
)="""
package ${packageName}
import androidx.lifecycle.viewModelScope
import com.bigademo.baselib.base.basemvvm.BaseViewModel
class ${activityClass}ViewModel : BaseViewModel() {
private val repo by lazy { ${activityClass}Repository(this, viewModelScope, errorLiveData) }
}
"""

7.编写mvvmActivityXml。这个文件是用于生成布局文件的

mvvmActivityXml.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package other.mvvm.activity.res.layout

fun mvvmActivityXml(
packageName: String,
activityClass: String
) = """
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>

</data>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}Activity">
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

8. 修改plugin.xml

  1. 添加org.jetbrains.android,org.jetbrains.kotlin,com.intellij.modules.java的依赖

  2. 修改applicationService和projectService的值

  3. 修改applicationListenersv中listener的值

  4. 添加wizardTemplateProvider为刚才添加的类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <idea-plugin>
    <id>com.bigaddemo.mvvm</id>
    <name>bigaddemo_MVVM</name>
    <vendor>bigademo</vendor>

    <!-- Product and plugin compatibility requirements -->
    <!-- https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html -->
    <depends>org.jetbrains.android</depends>
    <depends>org.jetbrains.kotlin</depends>
    <depends>com.intellij.modules.java</depends>
    <depends>com.intellij.modules.platform</depends>

    <extensions defaultExtensionNs="com.intellij">
    <applicationService serviceImplementation="com.bigaddemo.mvvm.services.MyApplicationService" />
    <projectService serviceImplementation="com.bigaddemo.mvvm.services.MyProjectService" />
    </extensions>

    <applicationListeners>
    <listener class="com.bigaddemo.mvvm.listeners.MyProjectManagerListener" topic="com.intellij.openapi.project.ProjectManagerListener" />
    </applicationListeners>

    <extensions defaultExtensionNs="com.android.tools.idea.wizard.template">
    <wizardTemplateProvider implementation="other.SamplePluginTemplateProviderImpl" />
    </extensions>
    </idea-plugin>

生成jar文件

在AS最上面选择运行Run plugin,成功以后即可在build/libs找见对应的jar文件。最后在AS的设置里将这个jar包添加的plugin,重启AS即可。
u
image-20210120191030327
image-20210120191055182

本网站由提供CDN加速