[译]Android Studio的Live Template
原作者: Reto Meier
文章来源:Medium
翻译:ztelur
译文仅供个人学习,不用于任何形式商业目的,转载请注明原作者、文章来源、翻译作者及简书链接,版权归原文作者所有。
如果你写过足够多的android代码,那么你总会犯过下边这段代码类似的错误。
Toast.makeText(MainActivity.this, "This will not be displayed");
如果我告诉你有一个方法可以保证你避免这些错误并且可以更高效的完成代码呢?
我说的神奇方法是什么?Live Template!
除非你是按照敲击键盘的次数来支付工资,否则没有人会想一直写重复且不变的代码。有些时候,展示效果比苦口解释更加有效,下面就是展示Live Template如何工作的例子。
Live Template 正如你所看到的,Live Template 是展示在代码完成选项中的快捷方式,当你选择它时,IDE就会插入一段代码片段,并让你在需要输入参数的地方进行后续输入。
举个例子,就上上图所显示的那样:输入"Toast"然后按Tab键插入一段关于Toast的新代码,并且留有你要输入的参数的占位符,再按下Tab键,光标会移动到下一个参数上。
Android Studio Live Template:速查表
IntelliJ IDE内置了很多Live Template,并且Android Studio又添加了转为Android开发者涉及的另外48个模版。下边就是我最喜欢的一部分模版:
Live TemplateLive Template也可以用于输入代码量更大的代码片段;比如创建一个静态
start(...)
方法来帮助启动Activity的starter
。
public static void start(android.content.Context context) {
android.content.Intent starter = new Intent(context, $ACT$.class);
starter.putExtra($CURSOR$);
context.startActivity(starter);
}
与此类似的还有:创建Fragment对象并传递参数的newInstance方法,为你自定义view添加构造函数的ViewConstructors。
你可以使用**File > Settings > Editor > Live Template ** 菜单选项来查看所有的模版。
当然,如果你最喜欢的模版不在其中的话,记住你可以:
建立自己的Live Template
译者注:此次有视屏,请执行翻墙查找Live Templates in Android Studio: Using and Creating Them
点击进入 ** File > Settings > Editor > Live Template ** 选择Android组,点击添加按钮来添加新的模版
你将要为模版来选择一个合适的缩写,并描述模版的作用,当然,还有你希望自动插入的代码-就像下边这个向Shared Preference中添加一个布尔值变量的例子一样.
android.content.SharedPreferences sharedPreferences =
getPreferences(Context.MODE_PRIVATE);
android.content.SharedPreferences.Editor editor =
sharedPreferences.edit();
editor.putBoolean(getString(R.string.$stringVal$), $spVal$);
editor.apply();
需要注意的是,我们使用了类的全限定类名。并且最为重要的是,你需要将模版中每次都可能变化,需要你输入的部分使用$符号括起来,这就是你使用模版时需要输入的变量。
当我们的模版定义好之后,我们可以键入它的缩写,从自动完成提示中选择它,预定的代码片段就是插入到我们的源文件中。
你将要向Live Template中添加什么样的代码呢?