我读到使用Anko的最大好处是它的可重用性.但我找不到它的确切例子.
目前在新的Android布局系统中,锅炉板如下:
DrawerLayout (with some setup) CoordinatorLayout (with some setup) AppBarLayout (with some setup) ToolBar <The Main Content> NavigationView (with header inflated)
从上面的布局结构中,仅< The Main Content>是varry.和
在许多情况下,这些仪式设置几乎在每个活动中都重复.
所以,Anko正在考虑是否有关于该问题的可重用解决方案.我不期望它可以重复用于通用布局,但至少我可以最小化项目中的仪式代码.也许我需要这样的东西:
class MainUI: AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View{ return with(ui) { myCustomRootLayout { //here is what <The Main Content> will be } } } }
从上面的代码我期望myCustomRootLayout将执行根布局的所有仪式设置,如(DrawerLayout,CoordinatorLayout等).
那可能吗?
编辑
所以我认为我的问题是:如何制作一个可以托管其他组件的自定义组件
解决方法
重用代码的一种方法是简单地将myCustomRootLayout提取到扩展方法中,如下所示:
class MainUI: AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View { return with(ui) { myCustomRootLayout { recyclerView() } } } } fun <T> AnkoContext<T>.myCustomRootLayout(customize: AnkoContext<T>.() -> Unit = {}): View { return relativeLayout { button("Hello") textView("myFriend") customize() } }
但是作为stated in the documentation:
Although you can use the DSL directly (in
onCreate()
or everywhere
else),without creating any extra classes,it is often convenient to
have UI in the separate class. If you use the provided AnkoComponent
interface,you also you get a DSL layout preview feature for free.
将可重用的部分提取到单独的AnkoComponent中似乎是个好主意:
class MainUI : AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View { return with(ui) { MyCustomRootLayout<MainActivity>({ recyclerView() }).createView(ui) } } } class MyCustomRootLayout<T : Context>(val customize: AnkoContext<T>.() -> Unit = {}) : AnkoComponent<T> { override fun createView(ui: AnkoContext<T>) = with(ui) { relativeLayout { button("Hello") textView("myFriend") customize() } } }