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.
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))
After digging up anko-support-v4
source code plus some trial and errors, I have found a workaround although I'm not sure if it's the right/recommended way. It seems a little undocumented.
A sample from my Fragment
code:
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return UI {
verticalLayout {
linearLayout {
avatar = imageView().lparams(width = dip(48), height = dip (48))
name = textView().lparams(width = 0, weight = 1f)
}
linearLayout {
// ...
}
}
}.toView()
}
I'm returning layout DSL wrapped in
UI { ... }.toView()
inFragment.onCreateView(...)
As of anko 0.8.1 the correct code would be:
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return UI {
verticalLayout {
linearLayout {
// ...
}
linearLayout {
// ...
}
}
}.view
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With