“Only the original thread that created a view hierarchy can touch its views.” error when using TimerTask

后端 未结 2 1203
忘了有多久
忘了有多久 2021-01-29 09:46

I have created an app composed of one single activity which include a single TextView. Here is the XML of my activity :

activity_main.xml

相关标签:
2条回答
  • 2021-01-29 10:39

    Your run() method will be called on a background thread, and it cannot manipulate the UI as a result.

    A lighter-weight solution would be:

    public class MainActivity extends AppCompatActivity {
        private TextView text;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            text = (TextView) findViewById(R.id.text_1);
    
            onEverySecond.run();
        }
    
        private Runnable onEverySecond=new Runnable() {
            @Override
            public void run() {
                text.setText("test");
                text.postDelayed(this, 1000);
            }
        }
    }
    

    postDelayed() calls your run() method on the main application thread, after the designated delay period. Here, we use that to have the Runnable schedule itself to run again after 1000ms.

    To stop the postDelayed() "loop", call removeCallbacks(onEverySecond) on your MainActivity.

    The advantage of this over using runOnUiThread() inside the TimerTask is that it is less expensive, as you are not creating a separate thread (the Timer/TimerTask thread).

    0 讨论(0)
  • 2021-01-29 10:44

    You need to perform

    text.setText("test");

    in UI thread. You can do so using Handlers.

    final Handler myHandler = new Handler();
    myHandler.post(myRunnable);
    
    
    
       final Runnable myRunnable = new Runnable() {
          public void run() {
            text.setText("test");
          }
       };
    
    0 讨论(0)
提交回复
热议问题