我是初学者... 为什么我的“setImageRessource”不起作用? 图像“fiole”必须在计时器持续时间的 10% 和 20% 时更改,但在我的手机上,图像永远不会更改...
但是,当时间等于持续时间的四分之一时,textViex 的文本会发生更改。
public class XActivity extends AppCompatActivity {
int duree;
String duration;
int durationInt;
protected TextView tempsRestant;
protected ImageView fiole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_X);
this.duree = 0;
this.duration = getIntent().getStringExtra("DURATION");
this.durationInt = Integer.parseInt(duration)*60;
this.tempsRestant=findViewById(R.id.tempsRestant);
this.fiole=findViewById(R.id.fiole);
final Timer modecTimer = new Timer();
modecTimer.schedule(new TimerTask() {
@Override
public void run() {
duree += 1;
if (duree==(durationInt/100)*10){
fiole.setImageResource(R.drawable.fiole10p);
}
if (duree==(durationInt/100)*20){
fiole.setImageResource(R.drawable.fiole20p);
}
if (duree==durationInt/4){
tempsRestant.setText("some text");
}
}
}
}, 1000, 1000);
}
最佳答案
您的setImageResource不起作用,因为它需要在UIThread上运行
modecTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(() -> {
duree += 1;
if (duree==(durationInt/100)*10){
fiole.setImageResource(R.drawable.fiole10p);
}
if (duree==(durationInt/100)*20){
fiole.setImageResource(R.drawable.fiole20p);
}
if (duree==durationInt/4){
tempsRestant.setText("some text");
}
});
}
}, 1000, 1000);
关于java - setImageRessource 在计时器 android studio 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128814/