有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android在运行任务时更新UI?

我以前问过,但没有得到任何有用的回答。 我有办法。我想通过该方法更新UI。我尝试在UI线程上运行代码,我尝试发布代码(.post[…]),我尝试过创建线程,但没有任何效果

下面是我的代码的简化版本:

int x;
for(int i = 0; i < times; i++){
    if((i % 2) == 1){
        x += (x / (x * 0.5));
    } else {
        x += (x / (x * 0.25));
    }
    while((System.currentTimeMillis() - t) < 2000){
        // wait
    }
    runOnUiThread(new Runnable(){
        @Override
        public void run(){
            btn.setText(x.toString());
        }
    }
} // The for loop won't update the UI until the entire method has finished.

就像我说的,创建一个新的线程/在UI线程上运行/发布没有帮助。 在方法运行时,如何更新UI

由于某种原因,UI将等待方法完成


共 (3) 个答案

  1. # 1 楼答案

    也许你应该使用AsyncTask

    AsyncTask具有方法onProgressUpdate(整数…)例如,您可以通过调用publishProgress()调用每个迭代,或者每次在doInBackground()期间完成一个进度

    android docs

  2. # 2 楼答案

    您可能想在这里使用AsynkTask。 可以是这样的

    class MyTask extends AsycnTask<Void,Integer,Void> {
        @Override
        protected Void doInBackground(Void... params) {
            for(int i = 0; i < times; i++){
                if((i % 2) == 1){
                    x += (x / (x * 0.5));
                } else {
                x += (x / (x * 0.25));
                }
                publishProgress(x);
            }
            return null;
        }
    
        @Override
        protected void onProgressUpdate(Integer... progress) {
            btn.setText(String.valueOf(progress[0]));
        }
    }
    

    然后在你的Activity{}。更多关于AsyncTaskhere

    但这种方法真的会导致UI线程冻结吗?如果你像在活动中那样调用它,它不是简单地更新值吗

  3. # 3 楼答案

    For some reason the UI will wait until the method has finished.

    您对setText()的调用会安排屏幕的更新,但在您将主应用程序线程的控制权返回到框架之前,更新无法进行。只要你绑住那条线,屏幕就不会更新

    How can I update the UI while a method is running?

    如果该方法与您的方法一样在主应用程序线程上运行,那么如果上面的代码段没有崩溃,则无法在运行时更新UI

    你可能想问一个新的堆栈溢出问题,解释一下你真正想做什么。在original question中,您引用了一个动画,但没有提供与该动画或runIntensiveMethod()的实现相关的代码