我想在一段时间后自动更改ListView的背景图像: 我使用这段代码:
在onCreate(_){
的一侧t = new Thread(){
public void run() {
for(int i=0; i<=5; i++){
Log.i("forrrrr ", i+"");
try {
if(flag == 0){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th2));
flag = 1;
}
else if(flag == 1){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th1));
flag = 0;
}
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
};
t.start();
}
但我在运行时遇到了以下异常:
05-31 13:30:23.832: INFO/AndroidRuntime(309): NOTE: attach of thread 'Binder Thread #3' failed
05-31 13:30:24.442: INFO/ARMAssembler(59): generated scanline__00000077:03545404_00000004_00000000 [ 47 ipp] (67 ins) at [0x2fc6d8:0x2fc7e4] in 5635232 ns
05-31 13:30:24.723: DEBUG/dalvikvm(315): GC_EXTERNAL_ALLOC freed 882 objects / 61160 bytes in 67ms
05-31 13:30:25.332: INFO/forrrrr(315): 0
05-31 13:30:25.452: DEBUG/dalvikvm(315): GC_EXTERNAL_ALLOC freed 248 objects / 11760 bytes in 113ms
05-31 13:30:25.992: INFO/ActivityManager(59): Displayed activity com.dev/.Android10Activity: 2234 ms (total 765300 ms)
05-31 13:30:27.675: INFO/forrrrr(315): 1
05-31 13:30:27.675: WARN/dalvikvm(315): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
05-31 13:30:27.675: ERROR/AndroidRuntime(315): FATAL EXCEPTION: Thread-8
05-31 13:30:27.675: ERROR/AndroidRuntime(315): java.lang.UnsupportedOperationException: removeAllViews() is not supported in AdapterView
05-31 13:30:27.675: ERROR/AndroidRuntime(315): at android.widget.AdapterView.removeAllViews(AdapterView.java:511)
05-31 13:30:27.675: ERROR/AndroidRuntime(315): at com.dev.Android10Activity$1.run(Android10Activity.java:61)
05-31 13:30:27.693: WARN/ActivityManager(59): Force finishing activity com.dev/.Android10Activity
如果我使用了一个按钮并手动更改,它就会像这样工作:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag == 0){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th2));
flag = 1;
}
else if(flag == 1){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th1));
flag = 0;
}
}
});
答案 0 :(得分:0)
您不能影响非“UI线程”的线程中的UI元素 您应该使用Activity.runOnUiThread运行此代码 或使用Handler
中的this example