【问题标题】:Set android background color async设置android背景颜色异步
【发布时间】:2016-09-01 20:47:56
【问题描述】:

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

颜色应该在一段时间后改变(这里是 500 毫秒)。我无法通过异步类访问视图或文本视图。

有什么办法吗?

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;
        }

【问题讨论】:

    标签: android android-activity view background-color


    【解决方案1】:

    使用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 线程。

    【讨论】:

    • 以这种方式工作:@Override protected Void doInBackground(Clock... params) { for(int i = 0; i &lt; 10; ++i) { final int c = i * 10; runOnUiThread(new Runnable() { @Override public void run() { setColor(c, 0, 0); } }); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }
    【解决方案2】:

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

    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);
    

    【讨论】:

    • 这段代码将postrunnable同时触发10次。
    • @F43nd1r 代码已更新。完成 for 循环后,runnable 将触发
    • 好吧,现在代码将产生无限的postDelayedcalls。
    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多