Is it possible to reuse a layout in Kotlin Anko

android, android-layout, anko, kotlin

Solution

One way to reuse the code is to simply extract `myCustomRootLayout` into a extension method like so:

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()
    }
}

However as 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.

It seems to be a good idea to extract the reusable piece into separate `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()
        }
    }
}

Problem

I read that the most benefit of using Anko is its reusability. But i could't find its exact example. Currently in the new Android layout system, the boiler plate is like below: ``` DrawerLayout (with some setup) CoordinatorLayout (with some setup) AppBarLayout (with some setup) ToolBar <The Main Content> NavigationView (with header inflated) ``` From the layout structure above, only `<The Main Content>` is varry. And in many cases those ceremonial setup duplicated almost in every activity. So here with Anko im thinking if there is a reusable solution about that issue. Im not expecting it will be reusable for general purpose layout, but et least i can minimize the ceremonial code in the project. Maybe i need something like: ``` class MainUI: AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View{ return with(ui) { myCustomRootLayout { //here is what <The Main Content> will be } } } } ``` From the code above im expecting `myCustomRootLayout` will do all the ceremonial setup for the root layout such as (DrawerLayout, CoordinatorLayout etc etc). Is that possible? EDIT So i think my question is: How to make a custom component which can host other component

Original source