Can someone give a simple example of updating a textfield every second or so?
I want to make a flying ball and need to calculate/update the ball coordinates every se
I Abstract Timer away and made it a separate class:
Timer.java
import android.os.Handler;
public class Timer {
IAction action;
Handler timerHandler = new Handler();
int delayMS = 1000;
public Timer(IAction action, int delayMS) {
this.action = action;
this.delayMS = delayMS;
}
public Timer(IAction action) {
this(action, 1000);
}
public Timer() {
this(null);
}
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (action != null)
action.Task();
timerHandler.postDelayed(this, delayMS);
}
};
public void start() {
timerHandler.postDelayed(timerRunnable, 0);
}
public void stop() {
timerHandler.removeCallbacks(timerRunnable);
}
}
And Extract main action from Timer
class out as
IAction.java
public interface IAction {
void Task();
}
And I used it just like this:
MainActivity.java
public class MainActivity extends Activity implements IAction{
...
Timer timerClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
timerClass = new Timer(this,1000);
timerClass.start();
...
}
...
int i = 1;
@Override
public void Task() {
runOnUiThread(new Runnable() {
@Override
public void run() {
timer.setText(i + "");
i++;
}
});
}
...
}
I Hope This Helps