https://kotlinlang.org logo
#android
Title
# android
n

nickk

01/16/2018, 2:39 PM
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

Roxana Nistor

01/16/2018, 2:54 PM
maybe you can try to do this example
n

nickk

01/16/2018, 2:57 PM
You mean, the problem is that I am creating the views in a function and not in-place?
r

Roxana Nistor

01/16/2018, 2:58 PM
maybe
n

nickk

01/16/2018, 3:03 PM
I tried this:
placeholder.addView( this.linearLayout { textView("Text 1")  })
and I am getting the same Exception.
r

Roxana Nistor

01/16/2018, 3:06 PM
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

nickk

01/16/2018, 3:16 PM
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

Roxana Nistor

01/16/2018, 3:17 PM
and it’s working?
n

nickk

01/16/2018, 3:17 PM
Yes
r

Roxana Nistor

01/16/2018, 3:17 PM
good
n

nickk

01/16/2018, 3:17 PM
Thanks!
So, I have to explicitly use an AnkoContext, I guess
r

Roxana Nistor

01/16/2018, 3:18 PM
welcome:) yep , seems like you did it:))
❤️ 1