2

我想在一段时间后自动更改 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;
                }               
            }
        });
4

1 回答 1

0

您不能从不是“UI 线程”的线程影响 UI 元素。您应该使用Activity.runOnUiThread
运行此代码 或使用本示例中的处理程序

这是另一篇可能有用的文章

于 2012-05-31T08:26:54.537 回答