1
我已经实现了一个可以执行各种API请求的类,我的想法是每个类的实例都有一个方法来创建一个具有类似接口的视图。Anko查看类
我的问题是我不知道如何实现这个好方法。
什么是使用Anko和Kotlin这样做的首选方式?
我已经实现了一个可以执行各种API请求的类,我的想法是每个类的实例都有一个方法来创建一个具有类似接口的视图。Anko查看类
我的问题是我不知道如何实现这个好方法。
什么是使用Anko和Kotlin这样做的首选方式?
安口有很大documentation about that case(但谁读文档,是吗?)
比方说,
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() }
但是如果你想用你的观点作为一个顶级窗口部件没有内部
Activity
一个UI 包装,添加此还有: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()
}
}
}
}
我已经阅读文档的一部分,但对我来说仍是对^ h不清楚ow使用这段代码片段。你有一个例子吗? – aul12
@ aul12增加了一个例子 –