设置 android 异步背景颜色

Set android background color async

我想更改 activity 异步背景(或更简单的文本视图背景)。

颜色应该在一段时间后改变(这里是 500 毫秒)。我无法通过异步 class.

访问视图或文本视图

有什么办法吗?

private void setColor(int red, int yellow, int blue) {
        View view = this.getWindow().getDecorView();
        view.setBackgroundColor(Color.rgb(red,yellow,blue));
    }

    private class DisplayGradient extends AsyncTask<Clock, Void, Void> {

        @Override
        protected Void doInBackground(Clock... params) {

            for(int i = 0; i < 10; ++i) {
                try {
                    setColor(i*10,0,0);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                return null;
        }

使用Activity.runOnUiThread.

UI 线程是唯一允许操作视图的线程。


或者,使用 View.postDelayed

view.postDelayed(new Runnable() {
        int count = 0;
        @Override
        public void run() {
            //do something on UI thread
            if(count++ < 10) {
                view.postDelayed(this, 500);
            }
        }
    }, 500);

这会自动使用 UI 线程。

试试这个简单的方法而不是你的代码。像这样

Handler handler = new Handler();

final Runnable r = new Runnable() {
public void run() {
    for(int i = 0; i < 10; ++i) {
            try {
                setColor(i*10,0,0);
                Thread.sleep(500)

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

     }
};

在您想开始的地方调用此行

handler.postDelayed(r, 500);