Android开发者的Anko使用指南(四)之Layouts

为什么不使用xml绘制Andoird的UI?

  • 类型不安全
  • 非空不安全
  • xml迫使你在很多布局中写很多相同的代码
  • 设备在解析xml时会耗费更多的cpu运行时间和电池
  • 最重要的时,它允许任何代码重用

简单案例

val act = this
val layout = LinearLayout(act)
layout.orientation = LinearLayout.VERTICAL
val name = EditText(act)
val button = Button(act)
button.text = "Say Hello"
button.setOnClickListener {
    Toast.makeText(act, "Hello, ${name.text}!", Toast.LENGTH_SHORT).show()
}
layout.addView(name)
layout.addView(button)
verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

findViewById()

val name = find<TextView>(R.id.name)
name.hint = "请输入你的姓名"
name.onClick{Toast(name.text)}

LayoutParams

使用lparams()描述布局参数,其中宽高都是wrapContent

linearLayout {
    button("Login") {
        textSize = 26f
    }.lparams(width = wrapContent) {
        horizontalMargin = dip(5)
        topMargin = dip(10)
    }
}
  • horizontalMargin 设置左右的边距
  • verticalMargin 设置上下的边距
  • margin 设置四周的边距
posted @ 2020-11-12 15:21  东骧神骏  阅读(210)  评论(0编辑  收藏  举报