我已经实现了一个执行各种 api 请求的类,我的想法是该类的每个实例都有一个方法来创建一个视图以具有类似平铺的界面。
我的问题是我不知道这应该如何以一种好的方式实现。
使用 Anko 和 Kotlin 的首选方法是什么?
Anko 有关于该案例的大量文档(但谁读过文档,是吗?)
比方说,
CustomView
是您的自定义View
类名,并且customView
是您要在 DSL 中编写的内容。如果您只打算
View
在被其他一些包围的 DSL中使用您的自定义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()
}
}
}
}