I made two timers. At some point one of them is increasing and other one is decreasing. I made two integers to increase/decrease every second and use setText
for TextView
. But for some reason it's not updating. I printed out integers and code was working but text isn't changing for TextView
. Here's my code:
TextView timerone, timertwo;
int turn = 1;
int timerOne = 20;
int timerTwo = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
timerone = findViewById(R.id.timerone);
timertwo = findViewById(R.id.timertwo);
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne ;
timerTwo--;
}else{
timerOne--;
timerTwo ;
}
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
}
CodePudding user response:
If you want to modify views from off the UI thread, you need to use runOnUiThread
or you will get an error. The following works to update the text views inside the loop.
TextView timerone = findViewById(R.id.timerone);
TextView timertwo = findViewById(R.id.timertwo);
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne ;
timerTwo--;
}else{
timerOne--;
timerTwo ;
}
runOnUiThread(() -> {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
});
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
Note, if your version of Java doesn't support lambdas, you can use this instead
runOnUiThread(new Runnable() {
@Override
public void run() {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
}
});
CodePudding user response:
Try this solution
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne ;
timerTwo--;
}else{
timerOne--;
timerTwo ;
}
// Here you will be updating textview's
runOnUiThread(new Runnable() {
@Override
public void run() {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
}
});
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();