this series aims to add varies app physical abilities with as little code lines inside the MainActivity. it is what the android studio IDEs should include as a default but they don't
so thank your lucky star I did it.
SoulTicker (java): this will run the code inside it's run method every tickMillies time
adding global variables to the class enables accessing them from within the tick.
- Code:
-
public class SoulTickerTest implements Runnable{
private Handler handler;
private TextView textView;
private PlayGround playGround =new PlayGround();
private int tickMilis = 1000;
public SoulTickerTest(Handler handler, TextView textView) {
this.handler = handler;
this.textView = textView;
}
public SoulTickerTest(Handler handler, TextView textView, int tickMilis) {
this.handler = handler;
this.textView = textView;
this.tickMilis = tickMilis;
}
public void turnOn(){handler.post(this);}
public void setTickMilis(int tickMilis) {
if(tickMilis<0){return;}
this.tickMilis = tickMilis;
}
@Override
public void run() {
textView.setText(playGround.getCurrentTimeStamp());
this.handler.postDelayed(this, tickMilis);
}
}
here is the exact same class but in kotlin :
- Code:
-
class SoulTickerTest:Runnable {
private val handler:Handler
private val textView:TextView
private val playGround = PlayGround()
private val tickMilis = 1000
constructor(handler:Handler, textView:TextView) {
this.handler = handler
this.textView = textView
}
constructor(handler:Handler, textView:TextView, tickMilis:Int) {
this.handler = handler
this.textView = textView
this.tickMilis = tickMilis
}
fun turnOn() {
handler.post(this)
}
fun setTickMilis(tickMilis:Int) {
if (tickMilis < 0) {
return
}
this.tickMilis = tickMilis
}
public override fun run() {
textView.setText(playGround.getCurrentTimeStamp())
this.handler.postDelayed(this, tickMilis)
}
}
here is how you use it from within the main class :
in the main class (kotlin):
val soulTickerTest = SoulTickerTest(Handler(),textView);
soulTickerTest.turnOn()
the textView var can be removed from the ticker, it's not a must.
the turnOn methode starts the ticking. the interval can be set as well using the
setTickMilis function.
_________________
MB over and out 