Android:用Button更新UI?

所以我有一些简单的代码,但它似乎没有工作..任何建议?

我只想在按下按钮后显示图像,然后在2秒后变为不可见。

button.setOnClickListener(new OnClickListener() { public void onClick(View v) { firstImage.setVisibility(ImageView.VISIBLE); // delay of some sort firstImage.setVisibility(ImageView.INVISIBLE); } } 

图像永远不会显示,它总是保持不可见,我应该以另一种方式实现吗? 我尝试过处理程序..但它没有用,除非我做错了。

永远不要让你的UI线程睡觉!

做这个:

 final Handler handler = new Handler(); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { firstImage.setVisibility(ImageView.VISIBLE); handler.postDelayed(new Runnable(){ public void run(){ firstImage.setVisibility(ImageView.INVISIBLE); } }, DELAY); } } 

在哪里设置DELAY为2000(ms)。

那么,您需要在两行之间添加延迟。 使用线程或计时器执行此操作。

单击按钮启动一个线程。 在run方法中,将ImageView的可见性更改为VISIBLE,然后将线程置于hibernate状态n秒,然后更改然后使其不可见。

要调用imageView的setvisibility方法,这里需要一个hanlder。

处理程序处理程序= new Handler();
 handler.post(new Runnable(){
     public void run(){
            image.setVisibiliy(可见);
           了Thread.sleep(200);
            image.setVisibility(不可见);
     }
 });

我知道这个问题已经得到了解答,但我想我会为喜欢我的人添加一个答案,偶然发现这个问题,寻找类似的结果,其中延迟是由一个过程而不是“睡眠”引起的

 button.setOnClickListener(new OnClickListener() { public void onClick(View v) { firstImage.setVisibility(ImageView.VISIBLE); // Run the operation on a new thread new Thread(new Runnable(){ public void run(){ myMethod(); returnVisibility(); } }).start(); } } private void myMethod() { // Perform the operation you wish to do before restoring visibility } private void returnVisibility() { // Restore visibility to the object being run on the main UI thread. MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { firstImage.setVisibility(ImageView.INVISIBLE); } }); }