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

后端 未结 6 2011
我寻月下人不归
我寻月下人不归 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:43

    A couple more solutions for old devices:

    TIMER

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Timer myTimer = new Timer();
        final View myview = getWindow().getDecorView().findViewById(
                android.R.id.content);
    
        myTimer.schedule(new TimerTask() {
            int color = 0;
            @Override
            public void run() {
                // If you want to modify a view in your Activity
                runOnUiThread(new Runnable() {
                    public void run() {
                        color++;
                        myview.setBackgroundColor(Color.argb(255, color, color,
                                color));
                        if (color == 255)
                            myTimer.cancel();
                    }
                });
            }
        }, 1000, 20); // initial delay 1 second, interval 1 second
    
    }
    

    THREAD

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Thread() {
            int color = 0;
            View myview = getWindow().getDecorView().findViewById(
                    android.R.id.content);
            @Override
            public void run() {
                for (color = 0; color < 255; color++) {
                    try {
                        sleep(20);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                myview.setBackgroundColor(Color.argb(255,
                                        color, color, color));
                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    

提交回复
热议问题