安科从课堂上看

我已经实现了一个类来执行各种api请求,我的想法是,每个类的实例都有一个方法来创建一个视图,使其具有类似的接口。

我的问题是我不知道这应该如何实施一个好方法。

使用Anko和Kotlin的最佳方式是什么?

Anko有关于这种情况的很好的文档 (但是谁读了文档,是啊?)

比方说, CustomView是你自定义的View类的名字,而customView是你想在DSL中写的东西。

如果您只打算在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() } } } }