AndroidStudio 子线程中无法操作UI

  今天在主线程开了一个子线程,如下代码

 public class MainActivity extends AppCompatActivity {
  Thread thread;
  boolean threadExit = false;

  public TextView tv1;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1 = (TextView)this.findViewById(R.id.textView2);
    thread = new Thread() {
       @Override
       public void run() {
         super.run();
         while (!threadExit) {
         tv1.setText("test");
         try {
             Thread.sleep(3000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
      }
    }
   };
  }
}

但是运行的时候却出现了以下问题,子线程中无法操作UI

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7313)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1161)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.support.constraint.ConstraintLayout.requestLayout(ConstraintLayout.java:3172)
        at android.view.View.requestLayout(View.java:21995)
        at android.widget.TextView.checkForRelayout(TextView.java:8531)
        at android.widget.TextView.setText(TextView.java:5394)
        at android.widget.TextView.setText(TextView.java:5250)
        at android.widget.TextView.setText(TextView.java:5207)
        at com.indemind.indeminddesktopapp.MainActivity$1.outputState(MainActivity.java:154)
        at com.indemind.indeminddesktopapp.MainActivity$1.run(MainActivity.java:76)

后查阅相关资料,发现可以在run()方法中发送消息,利用handler发送,首先创建一个内部类


 class  MyHandle extends Handler
 {
   @Override
   public void handleMessage(Message msg)
   {
     super.handleMessage(msg);
     String str = (String)msg.obj;
     tv1.setText(str);

   }
 }

然后,在子线程中

thread = new Thread() {
  @Override
  public void run() {
    super.run();
    while (!threadExit) {
     // tv1.setText("test");
     Message msg = Message.obtain();
     msg.obj ="TestSucceed"
     handle.sendMessage(msg);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
};

这样就可以在子线程中进行UI  setText(str)了

猜你喜欢

转载自blog.csdn.net/zjw1349547081/article/details/85265515