Updating UI / runOnUiThread / final variables: How to write lean code that does UI updating when called from another Thread

后端 未结 1 1701
旧时难觅i
旧时难觅i 2020-12-20 03:24

I have been reading up on the UI updating when I found out that, like WinForms, Android need to do UI updates on from the main thread (too bad, I was hoping someone could on

相关标签:
1条回答
  • 2020-12-20 04:11

    Try it:

    @Override 
    public void connStateChange(ClientHandler clientHandler) {
        final ClientHandler temporaryHander = clientHandler;
        runOnUiThread(new Runnable() {
             public void run() {
                   tv.append(temporaryHandler.getIP() + ", " + temporaryHandler.state.toString() + "\n"); 
                   if (temporaryHandler.state == State.Connected) {
                        tv.append("Loginserver hittad");         
                   }       
             }    
        }); 
    } 
    

    By the way, code becomes more readable, if you declare not anonim class right in the method, but declare inner class out of methods. Consider it as pattern Command.

    Example of more clean and reusable code.

    @Override 
    public void connStateChange(ClientHandler clientHandler) {
        final ClientHandler temporaryHander = clientHandler;
        runOnUiThread(new MyRunnableCommand(temporaryHandler)); 
    } 
    
    private class MyRunnableCommand implements Runnable { 
    
         private ClientHandler clientHandler;
    
         public MyRunnableCommand(ClientHandler clientHandler) {
             this.clientHandler = clientHandler;
         }
    
         @Override
         public void run() {
                   tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n"); 
                   if (clientHandler.state == State.Connected) {
                        tv.append("Loginserver hittad");         
                   }       
             } 
    
    }
    

    Though the Runnable implementation itself was inflated a little, code became more re-usable and easy to read.

    0 讨论(0)
提交回复
热议问题