繁体   English   中英

更改图像按钮的图像

[英]change image of imagebutton

我从android和java开始。

我尝试制作Simon游戏,但存在一些问题。

我编写此代码是为了显示simon按钮的顺序或玩家按下的按钮:

    if (but_num == 1) {
        ib1.setImageResource(R.drawable.bullet_square_green);
        MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_green);
        sound.start();
        for (int x = 1; x < 10000000; x++) { };
        ib1.setImageResource(R.drawable.bullet_ball_green);
    } else if (but_num == 2) {

它应该更改每个图像按钮的图像,播放声音,等待一段时间(用于{}),然后再次更改图像。

但是它不能很好地工作……它播放声音并确实通过bullet_square_xxx改变了图像,但是眼睛看不到图像的改变,只有当bullet_ball_xxx不再改变图像时,该改变才可见: -(

我认为这是我的错,因为我编写的代码与Java确实不同,但是我确实是个初学者,并且不打算在Java中思考。

谢谢,对不起我的英语!

这可能是由于事件分发线程上的延迟以及空循环甚至可能被编译器忽略的事实所致,因为它是静态的,因此很容易预测它对程序没有影响。 我的建议是首先在GUI上强制重新粉刷/更新并使用Thread.sleep。 像这样:

if (but_num == 1) {
    ib1.setImageResource(R.drawable.bullet_square_green);
    updateUI(); // if you are somewhere in a class extending any Frame/Panel
    //If you are in other class use mainFrame.repaint(); 
    MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_green);
    sound.start();
    try{
        Trhead.sleep(3000);
    } catch (InterruptedException e) {}
    ib1.setImageResource(R.drawable.bullet_ball_green);
    updateUI(); //only if this effect is delayed too
} else if (but_num == 2) {

好的...。我认为延迟是您代码中的问题。 如今,我可以做到的是,现在有高速处理器可以在几毫秒内达到10000000。 因此,与其使用老式的for循环来引入延迟使用,

Thread.sleep(5000);

这会导致5秒钟的延迟,参数是时间(以毫秒为单位)。

还有另一个线程讨论引入延迟: 如何在Android中暂停/休眠线程或进程?

您可以尝试此[我已从该线程复制粘贴]:

 if (but_num == 1) {
    ib1.setImageResource(R.drawable.bullet_square_green);
    MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_green);
    sound.start();

    // SLEEP 2 SECONDS HERE ...
Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
     public void run() { 
         ib1.setImageResource(R.drawable.bullet_ball_green);
     } 
}, 2000);


} else if (but_num == 2) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM