Runnable is posted successfully but not run

后端 未结 6 1575
别跟我提以往
别跟我提以往 2020-12-08 07:45

In an existing Android project I\'ve encountered the following piece of code (where I inserted the debugging litter)

ImageView img = null;

public void onCre         


        
6条回答
  •  攒了一身酷
    2020-12-08 08:23

    I think the problem is you are updating the UI (ImageView) with a separate thread, which is not the UI Thread. The UI can only be updated by the UI Thread.

    You can solve this by using Handler:

    Handler uiHandler;
    
    public void onCreate(){
        ...
        uiHandler = new Handler(); // This makes the handler attached to UI Thread
        ...
    }
    

    Then replace your:

    if ( !img.post(new Runnable() {
    

    with

    uiHandler.post(new Runnable() {
    

    to make sure the imageview is updated in the UI Thread.

    Handler is a quite confusing concept, I also took hours of research to really understand about this ;)

提交回复
热议问题