Reputation: 289
I have a textview which i want to change with a thread and do it again and again (Like a digital clock). But i'm having problems with setting time between 2 changes. Here, the code:
display1 = (TextView) findViewById(R.id.textView1);
Thread timer2 = new Thread(){
@Override
public void run() {
synchronized (this){
runOnUiThread(new Runnable() {
@Override
public void run() {
int i = 0;
display1.setText("" + i);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
display1.setText("" + (i+1));
}
});
}
}
};
timer2.start();
This sleep(2000); function makes textview invisible for the given time but i want it stand still till the next change. How can i do that?
Upvotes: 1
Views: 95
Reputation: 75635
But i'm having problems with setting time between 2 changes
Do NOT do sleep()
on your UI thread. If you want to chain some actions with the delay, split your code into two runnables and the first one should set display1
and then post second runnable with the delay using postDelayed()
EDIT
want one of them to increase 3 per sec, and the other 5 per sec until they reach 1000 for instance
You can make your Runnable post itself until some criteria are met (i.e. time, counter value etc). Just at the end your Runnable check your conditions and if not met, call postDelayed(this, delay);
and you are good.
Upvotes: 2
Reputation: 5986
You should use a Handler instead and dispatch your changes to the UI thread.
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
// Code to be run right away
}
});
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// Code to be run after 2 seconds
}
}, 2000);
Upvotes: 0
Reputation: 1248
Maybe split up what you need to do into separate methods. Here you have a UI method and a sleep method split up. Hope it helps
private void myMethod() {
new Thread() {
@Override
public void run() {
int i = 0;
doWorkOnUI(String.valueOf(i));
pause(2000);
doWorkOnUI(String.valueOf(i++));
}
}.start();
}
private void pause(int pauseTime) {
try {
Thread.sleep(pauseTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWorkOnUI(final String string) {
runOnUiThread(new Runnable() {
@Override
public void run() {
display1.setText(string);
}
});
}
Upvotes: -1