13.2 一个简单Anko视图

这里是一个转换成 Anko 的简单 XML 文件。

  1. <LinearLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_height="match_parent"
  4. android:layout_width="match_parent">
  5. <EditText
  6. android:id="@+id/todo_title"
  7. android:layout_width="match_parent"
  8. android:layout_heigh="wrap_content"
  9. android:hint="@string/title_hint" />
  10. <Button
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"
  13. android:text="@string/add_todo" />
  14. </LinearLayout>

用 Anko 描述的同样的视图

  1. verticalLayout {
  2. var title = editText {
  3. id = R.id.todo_title
  4. hintResource = R.string.title_hint
  5. }
  6. button {
  7. textResource = R.string.add_todo
  8. onClick { view -> {
  9. // 可以在这里添加一些处理逻辑
  10. title.text = "Foo"
  11. }
  12. }
  13. }
  14. }

可以看到在button布局中的onClick监听函数中,因为我们是使用 Kotlin代码来设计视图,所以可以直接使用title变量(editText视图对象)。