转载文章,出处: http://www.cnblogs.com/sunshine-anycall/p/5300305.html
Jetbrains 给 Android 带来的不仅是 Kotlin,还有 Anko。从 Anko 的官方说明来看这是一个雄心勃勃的要代替 XML 写 Layout 的新的开发方式。Anko 最重要的一点是引入了 DSL(Domain Specific Language)的方式开发 Android 界面布局。当然,本质是代码实现布局。不过使用 Anko 完全不用经历 Java 纯代码写 Android 的痛苦。因为本身是来自 Kotlin 的,所以自然的使用这种方式开发就具有了:
- 类型安全,不再需要那么多的
findViewById()
之后的类型转换。 - null 安全,Kotlin 里,如果一个变量用?表示为可空,并且使用?之后再调用的时候,即使变量为空也不会引发异常。
- 无需设备解析 XML,因为 Anko 本质是代码实现的界面和布局,所以省去了这些麻烦。
- 代码复用,可以通过继承
AnkoComponent
的方式实现代码复用。XML布局是每一个Activity,每一个View各自专属一个,代码复用比较少。
来一个列子看一下。为了不太墨迹,一些不必要的xml声明此处略去。
<RelativeLayout>
<TextView
android:id="@+id/sample_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Sample text view"
android:textSize="25sp" />
<Button
android:id="@+id/sample_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/sample_text_view"
android:text="Sample button" />
</RelativeLayout>
relativeLayout {
val textView = textView("Sample text view") {
textSize = 25f
}.lparams {
width = matchParent
alignParentTop()
}
button("Sample button").lparams {
width = matchParent
// 关键代码
below(textView)
}
}
网友评论