버튼이 속해 있는 Activity/Fragment에 Boolean 터압의 private 멤버변수를 두시고 Boolean값에 따라 동작을 분기해주시면 됩니다.
private var showButtonCaption = false // 클래스 멤버 변수
// 버튼 초기화
button.setOnClickListener {
toggleButtonCaption()
}
private fun toggleButtonCaption() {
// 버튼이 눌릴 때마다 Boolean 값을 바꾼다.
showButtonCaption = !showButtonCaption
button.text = if (showButtonCaption) {
"출력할 텍스트"
} else {
""
}
}
아래처럼 enum을 사용할 수도 있습니다.
enum class ButtonCaption(val caption: String) {
SHOW("출력할 텍스트") {
@Override
fun next() = CLEAR
},
CLEAR("") {
@Override
fun next() = SHOW
};
abstract fun next(): ButtonCaption
}
private var buttonCaption = ButtonCaption.CLEAR // 클래스 멤버 변수
// 버튼 초기화
button.setOnClickListener {
toggleButtonCaption()
}
private fun toggleButtonCaption() {
// 버튼이 눌릴 때마다 Enum 값을 바꾼다.
buttonCaption = buttonCaption.next()
button.text = buttonCaption.caption
}