Home > Net >  Adding buttons to view dynamically wipes existing views
Adding buttons to view dynamically wipes existing views

Time:12-27

I have a list of strings and I'd like to create buttons in a linear layout whose texts come from that list. My linear layout in the XML file is:

...other stuff...
<LinearLayout
    android:id="@ id/my_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"/>

Then in onCreate I have the following code:

buttons = viewModel.myLiveDataList.value!!.map {
    val button = Button(binding.myLinearLayout.context)
    button.layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT)
    button.text = it.displayName
    return button
}

I feel like I'm not doing this right because I never call addView on the linear layout, which all the examples I've seen do, but when I tried to call addView I got errors about the button already having a parent.

The result of this code is that the fragment displays only a single button whose text is the first entry of the list. It does not display the "other stuff" that exists before the linear layout and it does not display buttons for any other entries of the list.

I've verified with logging that the list itself does have multiple entries but the map function only executes on the first entry, and I don't know why everything else in the view is obliterated and I only get a single button.

Can anyone explain to me what I'm doing wrong?

Edit: As requested, I had originally tried to follow the example example output

  • Related