In Android, how do I smoothly fade the background from one color to another? (How to use threads)

后端 未结 6 2013
我寻月下人不归
我寻月下人不归 2020-12-23 09:59

I\'ve been playing with Android programming on and off for a couple of weeks, and I\'m trying to get something to work that seems simple, but I think I am missing something.

6条回答
  •  無奈伤痛
    2020-12-23 10:30

    In your loop, your setting on background is so fast that the UI is not (will not) able to schedule the update of display. Yes, you better use a second thread to update the background or else you will stall the UI thread. Try following:

    LinearLayout screen;
    Handler handler = new Handler();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        screen = (LinearLayout) findViewById(R.id.screen);
    
        (new Thread(){
            @Override
            public void run(){
                for(int i=0; i<255; i++){
                    handler.post(new Runnable(){
                        public void run(){
                            screen.setBackgroundColor(Color.argb(255, i, i, i));
                        }
                    });
                    // next will pause the thread for some time
                    try{ sleep(10); }
                    catch{ break; }
                }
            }
        }).start();
    }
    

    This is a threaded version of your code.

提交回复
热议问题