是否可以在Kotlin Anko中重复使用布局

ktu*_*nik 7 android android-layout kotlin anko

我读到使用Anko的最大好处是它的可重用性.但我找不到它的确切例子.

目前在新的Android布局系统中,锅炉板如下:

DrawerLayout (with some setup)
   CoordinatorLayout (with some setup)
      AppBarLayout (with some setup)
         ToolBar
      <The Main Content>
   NavigationView (with header inflated)
Run Code Online (Sandbox Code Playgroud)

从上面的布局结构来看,只有<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
        }
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

从上面的代码我期望myCustomRootLayout将完成根布局的所有仪式设置,如(DrawerLayout,CoordinatorLayout等).

那可能吗?

编辑 所以我认为我的问题是:如何制作一个可以托管其他组件的自定义组件

mie*_*sol 4

重用代码的一种方法是简单地提取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()
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,正如文档中所述

尽管您可以直接使用 DSL(在其他地方onCreate()或在其他地方),而无需创建任何额外的类,但在单独的类中拥有 UI 通常会很方便。如果您使用提供的 AnkoComponent 接口,您还可以免费获得 DSL 布局预览功能。

将可重用的部分提取到单独的部分似乎是个好主意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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)