마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

동적으로 생성한 버튼 삭제하는법

0 추천
이제 공부한지 몇달 안된 초보인데요 ...

삭제버튼을 눌렀을 때 버튼이 삭제되게 하고 싶은데..

삭제하는 메소드를 아무리 검색해도 못찾겠어서요 ㅠㅠ
qqwe7789 (160 포인트) 님이 2021년 5월 17일 질문

1개의 답변

0 추천

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
}

 

 

spark (224,800 포인트) 님이 2021년 5월 17일 답변
아 적어주신 답변보고 해결 했습니다 정말 감사합니다!
...