2013-02-25 43 views
3

这里是我的代码:在Android中,如何更改按钮的颜色,暂停几秒钟,然后再次更改它?

public class TestActivity extends Activity {  

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     start(); 
    } 

    private void start() { 
     setContentView(R.layout.main); 

     LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout); 

     Button button = new Button(this); 

     layout.addView(button); 

     button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x0000FF00)); // green 
     button.invalidate(); 

     try { 
      Thread.sleep(3000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     button.getBackground().setColorFilter(new LightingColorFilter(0x00000000, 0x000000FF)); // blue 
     button.invalidate(); 
    } 
} 

这短短3秒后显示一个蓝色按钮;它从不显示为绿色。

我想,如果我的大脑正常工作,我可以从这些职位之一找出答案:

Why isn't view.invalidate immediately redrawing the screen in my android game

How to force a view to redraw immediately before the next line of code is executed

How to force an entire layout View refresh?

回答

2

你不应该睡在UI线程上,因为这会挂起你的界面。相反,在最初将颜色设置为绿色后,您可以创建一个处理程序(在UI线程上,因此它将使用该线程处理消息),然后使用Handler.postDelayed发送将在3秒内处理的消息。在Runnable中,您传递给postDelayed您可以将颜色设置为蓝色。

1

你在睡觉的主在设置颜色后,UI几乎立即进入线程。这意味着线程在获得重绘机会之前被锁定。

对此的一个解决方案是使用线程。设置背景颜色,然后使用另一个线程进入睡眠状态,完成后调用主(UI)线程再次更改颜色。

您可以尝试查找AsyncTaskThreading