setText is not working inside a while loop

和自甴很熟 提交于 2019-12-13 09:26:22

问题


why is that?

while (flag) {
outCPU.setText(getCpuInfo());
}

getCpuInfo returns string, if I try to write this method's return out into a log, there is everything that should be, but nothing happens to textview..


回答1:


It will not work... display will update after your function finishes. Try this

boolean flag;
private void updateTextView(){
     outCPU.setText(getCpuInfo());
     if(flag){
         outCPU.post(new Runnable(){
             public void run(){
                 updateTextView();
             }
         });
     }
}

private void your_function(){
    if(flag){
         outCPU.post(new Runnable(){
             public void run(){
                 updateTextView();
             }
         });
     }

}



回答2:


The infinite loop on the ui thread it is not probably a good idea. setText schedule a draw operation, posting on the ui thread queue. Unfortunately the same thread is busy looping. You could use the TextView's internal handler to post a Runnable on the ui thread's queue. E.g.

private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        if (!flag) {
            outCPU.removeCallbacks(this);
            return;
        }
        outCPU.setText(getCpuInfo());
        outCPU.postDelayed(this, 200);
    }
};

and in place of your while loop you simply do

outCPU.post(mRunnable);


来源:https://stackoverflow.com/questions/30128664/settext-is-not-working-inside-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!