2

so i was trying to mess around with android studio, and decided to make a simple counter app. Every time I press the button(which covers the entire screen) it adds 1, and if i keep the button pressed for 3 sec the counter resets. Simple as that. But unfortunately, can't seem to get the setOnChronometerTickListener to work, and i need it to see when the chronometer reaches 3s. The code I have is here below:

var button = findViewById<Button>(R.id.button)
val chrono = Chronometer(this)

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

    button.setOnTouchListener(OnTouchListener { v , event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> { chronoStart()}
            MotionEvent.ACTION_UP -> { chrono.stop()}
        }
        false
    })

}

fun chronoStart() {

    chrono.start()

    chrono.setOnChronometerTickListener() {}
}

var counter = 0;

fun count(view: View){

    val button = view as Button

}

I already tried

chrono.setOnChronometerTickListener(chrono.onChronometerTickListener!!) {}

also tried another code I saw online, but it wasn't up to date. Any ideas on how to solve this problem or even a different way to accomplish the same result?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Migaloco
  • 31
  • 7

1 Answers1

0

Here is what worked for me.

I have used the interface Chronometer.OnChronometerTickListener at activity

package com.demo.tappycounterappy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.SystemClock
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Chronometer
import android.widget.TextView

class MainActivity : AppCompatActivity(), Chronometer.OnChronometerTickListener {

    private lateinit var _chronometerTimer:Chronometer

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

        _chronometerTimer = findViewById(R.id.chronometer_timer)
        _chronometerTimer.base = SystemClock.elapsedRealtime() + 5000
        _chronometerTimer.setOnChronometerTickListener(this)
        _chronometerTimer.start()


    }

    override fun onChronometerTick(chronometer: Chronometer){
        Log.e("onChronometerTick", "called")
    }
}

I have tested it and my onChronometerTick function is called every sec.

Note: and yes as you said. below code doesn't work

_chronometerTimer.setOnChronometerTickListener ( Chronometer.OnChronometerTickListener {

            fun onChronometerTick(chronometer:Chronometer) {
               Log.e("onChronometerTick", "called")
            }

        })
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124