Accessing views from other thread (Android)

前端 未结 5 1021
小蘑菇
小蘑菇 2020-12-19 07:21

I\'m developing an android application, and I have a button which starts/pauses certain simulation process. While this process is running, I need to output some data from it

5条回答
  •  悲&欢浪女
    2020-12-19 07:51

    They can be accessed but only read-only. What you mean is you want to trigger changes from a thread on the views. From the worker thread (non-UI) these changes cannot be triggered, you need to use .runOnUiThread() or use Handlers. Use these at the point where you want to show something, e.g update the textview in .runOnUiThread(),

    Example:

    myThread = new Thread()
            {
    
                @Override
                public void run() {
                    //yourOperation
                    MyActivity.this.runOnUiThread(new Runnable(){
    
                        @Override
                        public void run() {
                            if(e!=null)
                            {
                                myTextView.setText("something");
                            }
    
                        }});
                    super.run();
                }
            };
            myThread.start();
    

提交回复
热议问题