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

最佳答案

您不能通过不是“ UI线程”的线程来影响UI元素。
您应该使用Activity.runOnUiThread运行此代码
或使用Handler中的this example

这是另一个article that may be useful

关于android - 自动更改ListView的背景图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10829711/

10-12 02:40