Android
主页 > 软件编程 > Android >

Kotlin之自定义Live Templates详解(模板代码)

2020-03-17 | 秩名 | 点击:
想必大家都知道 android studio 的 live templates 功能,那真是各种方便,比如你想使用 newInstance 去生成一个类的实例:

-[-/a>

简直不要太方便!

当今 kotlin 流行起来了,你在使用 kotlin 开发 android 的时候,是不是发现以前用的 logt、loge、newinstance…,这些快捷创建代码片段的方式都不能用了,没关系,来一起自定义吧年轻人~

打开 android studio >> File >> Settings ,搜索 “live templates”:

-[-/a>

来看看我们之前在 java 代码里用的 newinstance 到底是怎么定义的:

-[-/a>

现在,我们就可以照着葫芦画瓢,来把 newinstance 搬到 kotlin 里边了:

首先先明确我们最终要生成的代码:

?
1
2
3
4
5
6
7
8
9
10
companion object {
 fun newInstance(): TestKotlinFragment {
 
 val args = Bundle()
 
 val fragment = TestKotlinFragment()
 fragment.arguments = args
 return fragment
 }
}

然后就可以照着 java 版的 newinstance 模板去写 kotlin 版的了:

-[-/a>

gif图太长了,再来个静态的:

-[-/a>

下面是 template text,需要的直接复制。。:

?
1
2
3
4
5
6
7
8
9
10
companion object {
 fun newInstance($args$): $fragment$ {
 $nullChecks$
 val args = android.os.Bundle()
 $addArgs$
 val fragment = $fragment$()
 fragment.arguments = args
 return fragment
 }
}

最后再来个 kotlin 中使用的效果:

-[-/a>

到这里就结束了,如果你想自定义其他的,照着这个方法就可以,本文就不演示其他的了。


原文链接:https://blog.csdn.net/Captive_Rainbow_/article/details/79642244
相关文章
最新更新