anko
如果不了解anko 的 可以去上面的鏈接看下anko 如何寫布局的虏杰。
簡單實現(xiàn)
首先,Kotlin的擴展函數(shù)功能是我們實現(xiàn)anko 的基礎(chǔ)條件勒虾。
以下實現(xiàn)一個 ViewGroup (LinearLayout) 和 一個 View (TextView)
View 的最簡單創(chuàng)建需要 Context纺阔,可能是 Activity 的 或者是 View Parent 的。
所以我們需要對 Context ViewGroup 進行擴展修然。(以下代碼都是 在 Ui.kt 下面建的)
private inline fun <reified T : View> Context.handleView(view: T, init: T.() -> Unit): T{
view.init()
return view
}
private inline fun <reified T : View> ViewGroup.handleView(view: T, init: T.() -> Unit): T{
view.init()
this.addView(view)
return view
}
如果是從ViewGroup 來的話 還需要把控件添加上去州弟。
接著寫一個 LinearLayout 和 TextView 的擴展
fun Context.linearLayout(init : LinearLayout.() -> Unit): LinearLayout {
return this.handleView(LinearLayout(this), init)
}
fun ViewGroup.linearLayout(init : LinearLayout.() -> Unit): LinearLayout {
return this.handleView(LinearLayout(this.context), init)
}
fun Context.text(init : TextView.() -> Unit): TextView{
return this.handleView(TextView(this), init)
}
fun ViewGroup.text(init : TextView.() -> Unit): TextView{
return this.handleView(TextView(this.context), init)
}
然后寫一個布局參數(shù)
fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
marginTop: Int = 0,
marginLeft: Int = 0,
marginRight: Int = 0,
marginBottom: Int = 0
): T {
val layoutParams = LinearLayout.LayoutParams(width, height)
layoutParams.setMargins(marginLeft, marginTop, marginRight, marginBottom)
this.layoutParams = layoutParams
return this
}
寫 onClick
fun android.view.View.onClick(l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
寫 padding
fun noGetter(): Nothing = throw IllegalAccessException("Property does not have a getter")
var android.view.View.padding : Int
set(value) {
setPadding(value, value, value, value)
}
@Deprecated("Property does not have a getter", level = DeprecationLevel.ERROR)
get() = noGetter()
現(xiàn)在就可以使用了
val layout = linearLayout {
orientation = LinearLayout.VERTICAL
padding = 40
text {
text = "H0"
textSize = 16f
onClick {
}
}
linearLayout {
lparams(marginTop = 30)
orientation = LinearLayout.HORIZONTAL
text {
text = "H1"
}
text {
lparams(marginLeft = 20)
text = "H2"
}
}
}
container.addView(layout)
當然也可以擴展 Activity 然后直接添加到 content view 上面钧栖,我這里沒寫。