class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvCount : TextView = findViewById(R.id.tv_count)
val btnStart : Button = findViewById(R.id.btn_start)
val btnEnd : Button = findViewById(R.id.btn_end)
var timerTask : Timer? = null //Nullable 타입
var sec : Int = 0
btnStart.setOnClickListener {
timerTask = kotlin.concurrent.timer(period = 1000) {
sec++
runOnUiThread {
tvCount.text = sec.toString() //Int -> String
}
}
}
btnEnd.setOnClickListener {
timerTask?.cancel() //Nullable 타입이기 때문에 변수 사용 시 ?를 붙여야 한다.
}
}
}
시작 버튼과 종료 버튼을 만들어 타이머를 조절하는 코드이다.
Nullable 타입을 사용할 때 주의해야 한다.
'Android Studio' 카테고리의 다른 글
Firebase 연동 시 SHA-1값 알아보기 (0) | 2022.07.30 |
---|---|
1. Button으로 TextView 변환 (0) | 2022.07.24 |
댓글