API 문서를 보면, 아래의 두 메소드가 있습니다.
https://developer.android.com/reference/android/view/ViewGroup#removeView(android.view.View)
https://developer.android.com/reference/android/view/ViewGroup#removeViewAt(int)
이걸 활용하시면 될 것 같은데요.
코틀린으로 간단한 샘플코드를 작성해 봤습니다.
private val buttonContainerView: ViewGroup by lazy {
findViewById(R.id.buttonContainerView)
}
pivate val buttons = arrayListOf<Button>()
private val lastCreatedButton: Button? = null
get() = buttons.lastOrNull()
private fun createButton() {
Button(context).also { button ->
button.text = "Text"
buttonContainerView.add(button)
buttons.add(button)
}
}
private fun removeButton(button: Button) {
buttonContainerView.remove(button)
}
private fun clearButtons() {
buttonContainerView.removeAll()
buttons.clear()
}
// Remove last created button
lastCreatedButton?.also { button ->
removeButton(button)
}
val button = buttonContainerView 안에 있는 버튼만 가져오는 다른 방법으로는 buttonContainerView의 childview 에서 버튼만 가져오셔도 될 듯합니다.
// KTX 함수
val button = buttonContainerView.children.filterInstance<Button>
val button = (0 until buttonContainerView.childCount).mapNotNull { childView ->
if (childView is Button) childView else null
}