Herkese merhaba.

Bu yazımızda Android Studio’da Kotlin kullanarak CountDownTimer metodunu inceleyeceğiz. İlk olarak değişkenlerimizi tanımlıyoruz.

private lateinit var timer: CountDownTimer
private var secondsRemaining: Long = 10

Burada secondsRemaining değişkeni sayacın kaç saniye çalışacağıdır. Daha sonra OnCreate() metodu içerisine

val text = findViewById<TextView>(R.id.text) as TextView
timer = object : CountDownTimer(secondsRemaining * 1000, 1000) {
    override fun onFinish(){}
    override fun onTick(millisUntilFinished: Long) {
        secondsRemaining = millisUntilFinished / 1000
        text.setText(secondsRemaining.toString())
    }
}.start()

CountDownTimer kodumuz bu kadar. Şimdi kodun tamamına göz atalım.

Kodlar : MainActivity.kt

package com.can.deneme

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    private lateinit var timer: CountDownTimer
    private var secondsRemaining: Long = 10

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val text = findViewById<TextView>(R.id.text) as TextView
        timer = object : CountDownTimer(secondsRemaining * 1000, 1000) {
            override fun onFinish(){}
            override fun onTick(millisUntilFinished: Long) {
                secondsRemaining = millisUntilFinished / 1000
                text.setText(secondsRemaining.toString())
            }
        }.start()
    }
}

Kodlar : activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.526" />

</android.support.constraint.ConstraintLayout>