【发布时间】:2017-02-24 15:18:23
【问题描述】:
我已经实现了一个执行各种 api-request 的类,我的想法是该类的每个实例都有一个方法来创建一个视图以具有类似平铺的界面。
我的问题是我不知道应该如何以一种好的方式实现它。
使用 Anko 和 Kotlin 的首选方式是什么?
【问题讨论】:
我已经实现了一个执行各种 api-request 的类,我的想法是该类的每个实例都有一个方法来创建一个视图以具有类似平铺的界面。
我的问题是我不知道应该如何以一种好的方式实现它。
使用 Anko 和 Kotlin 的首选方式是什么?
【问题讨论】:
Anko 的 documentation about that case 很棒(但谁读过文档,是吗?)
假设
CustomView是您的自定义View类名,并且customView是你想在 DSL 中写的。如果您只打算在 DSL 中使用自定义
View其他一些View:inline fun ViewManager.customView(theme: Int = 0) = customView(theme) {} inline fun ViewManager.customView(theme: Int = 0, init: CustomView.() -> Unit) = ankoView({ CustomView(it) }, theme, init)所以现在你可以这样写:
frameLayout { customView() }…或者这个(参见 UI 包装器章节):
UI { customView() }但是,如果您想将视图用作没有 UI 的顶级小部件
Activity中的包装器,也添加这个:inline fun Activity.customView(theme: Int = 0) = customView(theme) {} inline fun Activity.customView(theme: Int = 0, init: CustomView.() -> Unit) = ankoView({ CustomView(it) }, theme, init)
示例(我就是这么用的,你可以选择不同的方法):
class YourAwesomeButton: Button() {
/* ... */
fun makeThisButtonAwesome() {/* ... */}
}
/** This lines may be in any file of the project, but better to put them right under the button class */
inline fun ViewManager.yourAwesomeButton(theme: Int = 0) = yourAwesomeButton(theme) {}
inline fun ViewManager.yourAwesomeButton(theme: Int = 0, init: CustomView.() -> Unit) =
ankoView({ YourAwesomeButton(it) }, theme, init)
在另一个文件中:
class YourAwesomeActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(saveInstanceState)
relativeLayout(R.style.YourAwesomeAppTheme) {
yourAwesomeButton(R.style.YourAwesomeAppTheme) {
makeThisButtonAwesome()
}.lparams {
centerInParent()
}
}
}
}
【讨论】: