【问题标题】:postDelayed handler with loop [duplicate]带有循环的 postDelayed 处理程序[重复]
【发布时间】:2019-05-17 07:00:32
【问题描述】:

我做了一些研究并尝试了一些代码,包括来自Android postDelayed Handler Inside a For Loop? 的以下代码。

final Handler handler = new Handler(); 


    int count = 0;
    final Runnable runnable = new Runnable() {
        public void run() { 

            // need to do tasks on the UI thread 
            Log.d(TAG, "runn test");


            if (count++ < 5)
                handler.postDelayed(this, 5000);

        } 
    }; 

    // trigger first time 
    handler.post(runnable);

但是 count 变量会显示错误,因为它是在内部类中访问的。我该如何解决这个问题?

【问题讨论】:

    标签: java android android-handler


    【解决方案1】:

    从内部类中访问变量“count”,需要是最终的或有效的最终

    您需要将 count 转换为最终的 One 元素数组

    final Handler handler = new Handler();
    
    final int[] count = {0};        //<--changed here
    final Runnable runnable = new Runnable() {
        public void run() {
    
            // need to do tasks on the UI thread
            Log.d(TAG, "runn test");
    
    
            if (count[0]++ < 5)     //<--changed here
                handler.postDelayed(this, 5000);
    
        }
    };
    
    // trigger first time
    handler.post(runnable);
    

    【讨论】:

    • 你得到答案了吗?
    • 这样正常吗?还是应该尽可能避免?
    • 如果您想访问该变量,这是必要的
    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 2015-05-12
    • 1970-01-01
    • 2012-01-08
    • 2016-05-01
    • 2019-02-04
    • 2016-06-27
    • 2014-02-21
    相关资源
    最近更新 更多