Best way to make universal AppBar with Anko DSL?


#1

I’m trying to make a toolbar that I can insert into other Anko components. Here is an example of what I am going for:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MainUI().setContentView(this)

        val toolbar: Toolbar = find(R.id.toolbar)
        setSupportActionBar(toolbar)
    }
}

class MainUI : AnkoComponent<MainActivity> {
    override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
        coordinatorLayout {
            fitsSystemWindows = true
            lparams {
                width = matchParent
                height = matchParent
            }
            ToolbarUI().createView(ui).lparams { width = matchParent }
            recyclerView {...}.lparams {
                width = matchParent
                height = matchParent
                behavior = AppBarLayout.ScrollingViewBehavior()
            }
        }
    }
}

class ToolbarUI : AnkoComponent<AppCompatActivity> {
    override fun createView(ui: AnkoContext<AppCompatActivity>) = with(ui) {
        appBarLayout {
            ...
            toolbar {
                setTitleTextColor(Color.WHITE)
                id = R.id.toolbar
                title = resources.getString(R.string.main_activity)
                ...
            }.lparams {
                width = matchParent
                height = wrapContent
            }
        }
    }
}

But I am getting this:
java.lang.IllegalStateException: View is already set: org.jetbrains.anko.design._AppBarLayout

This way I could use this same AppBarLayout elsewhere with much less code. Anyone could help me with the correct way to implement this?