Is there any example, how to inject an anko genera...
# android
n
Is there any example, how to inject an anko generated view/layout into a layout inflated from XML? I have a placeholder (
FrameLayout
) in my XML layout and I want to populate it with an unknown number of `TextView`s, programmatically, at runtime. I tried something like:
placeholder.addView(xxx)
, where xxx is a VerticalLayout created using anko, but I am getting the Exception:
java.lang.IllegalStateException: The specified child already has a parent
I create the VerticalLayout with this function:
Copy code
fun createTextViews() : View {
        return verticalLayout {
            textView {
                text = "TextView 1"
            }

            textView {
                text = "TextView 2"
            }
        }

    }
r
maybe you can try to do this example
n
You mean, the problem is that I am creating the views in a function and not in-place?
r
maybe
n
I tried this:
placeholder.addView( this.linearLayout { textView("Text 1")  })
and I am getting the same Exception.
r
and if you try like this:
override fun createView(ui: AnkoContext<MainActivity>): View = with(ui) { return relativeLayout { val emptyView = textView(“Say something outrageous.“) { textSize = 16f typeface = Typeface.MONOSPACE }.lparams { centerInParent() }
n
This is (almost) correct! Here is my version:
Copy code
fun createView(ui: AnkoContext<Context>): View = with(ui) {
        return relativeLayout {
            val emptyView = textView("Say something outrageous.") {
                textSize = 16f
                typeface = Typeface.MONOSPACE
            }.lparams {
                centerInParent()
            }
        }
    }
r
and it’s working?
n
Yes
r
good
n
Thanks!
So, I have to explicitly use an AnkoContext, I guess
r
welcome:) yep , seems like you did it:))
❤️ 1