Reputation: 13
What I am trying to do is restart the CountdownTimer object when it is finished. Therefor I put it inside a procedure 'goCountdown', so onFinish() it calls itself. However this gives the following problems:
- A procedure goCountdown cannot be called from within the same class
- B activity text cannot be updated with time from outside the MainActivity class.
See references '!!! nr !!!' in code below:
Questions:
Besides my goal to make the timer loop I am trying to understand why it is not working. Thanks for explaining or pointing me to the explanation.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tapAction.setOnClickListener{
boTimeRunning = !boTimeRunning
if(boTimeRunning ){
goCountdown() //!!! 1 !!! its fine to call it from here when its outside the class
}
}
//!!! 2 !!!but if fun goCountdown() block is placed here, it is not seen at !!! 1 !!! place
}
}
fun goCountdown(){
object : CountDownTimer1(timeSettings_set * 1000, 1000){
override fun onTick(p0: Long) {
MainActivity.txtBig.text = "sometext" //!!! 3 !!!this doesnt work, also when MainActivity is declared as a variable object.
}
override fun onFinish() {
goCountdown() //primary goal: restart the timer when its done
}
}.start()
}
Upvotes: 0
Views: 1522
Reputation: 401
Is txtBig kotlin synthetic view or a local variable or global variable?
if txtBig is kotlin synthetic view, you should be able to call it.
if txtBig isn't kotlin synthetic veiw, try this code.
class MainActivity : AppCompatActivity() {
private lateinit var txtBigcopy: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
txtBig = findViewById<TextView>(R.id.txt_big) // Your id in xml
txtBigcopy = txtBig
tapAction.setOnClickListener{
boTimeRunning = !boTimeRunning
if(boTimeRunning ){
goCountdown()
}
}
}
fun goCountdown(){
object : CountDownTimer1(timeSettings_set * 1000, 1000){
override fun onTick(p0: Long) {
txtBigcopy.text = "sometext"
}
override fun onFinish() {
goCountdown()
}
}.start()
}
}
Upvotes: 1