我是初学者... 为什么我的“ setImageRessource”不起作用? 图片“坏蛋”必须在计时器持续时间的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);
}
答案 0 :(得分:0)
您的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);