How to use Anko DSL inside a Fragment?

akhy picture akhy · Nov 16, 2015 · Viewed 8.5k times · Source

The Github wiki page show this example to be used in Activity instance:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }
}

How to do the same inside a Fragment?

I tried to put that verticalLayout block in onCreateView but the method cannot be resolved. I have added anko-support-v4 dependency, but still no luck.

Answer

RussHWolf picture RussHWolf · Dec 27, 2015

With Anko 0.8 you can also use an AnkoComponent, if you want to hold your UI in a separate class so you can reuse it elsewhere.

class FragmentUi<T>: AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            // ...
        }
    }
}

You can call it in your fragment onCreateView() by

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View
        = FragmentUi<Fragment>().createView(AnkoContext.create(ctx, this))