我正在尝试更改相对布局背景颜色,例如闪烁首先设置为绿色,然后在相对布局中设置白色背景颜色。但是,我的问题线程执行第二次强制关闭错误并尝试修复很多方法但不起作用。这是我的代码:
isThreadRunning = true;
relative=(RelativeLayout) findViewById(R.id.layout);
Runnable runnable = new Runnable() {
public void run() {
int i=0;
while(isThreadRunning) {
if(i==0)
{
relative.setBackgroundColor(Color.GREEN);
i=1;
}
else
{
relative.setBackgroundColor(Color.BLACK);
i=0;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
我在 logcat 中遇到错误,如下所示:
07-10 17:48:42.752: W/dalvikvm(2060): threadid=9: thread exiting with uncaught exception (group=0x40015560)
07-10 17:48:42.756: E/AndroidRuntime(2060): FATAL EXCEPTION: Thread-10
07-10 17:48:42.756: E/AndroidRuntime(2060): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.invalidate(View.java:5279)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.setBackgroundDrawable(View.java:7626)
07-10 17:48:42.756: E/AndroidRuntime(2060): at android.view.View.setBackgroundColor(View.java:7516)
07-10 17:48:42.756: E/AndroidRuntime(2060): at com.example.screen_blinker.Home_activity$1.run(Home_activity.java:44)
07-10 17:48:42.756: E/AndroidRuntime(2060): at java.lang.Thread.run(Thread.java:1019)
我的代码有什么问题以及如何解决这个问题?
提前致谢!