我试图在动态添加视图到另一个视图在MainActivity:当新线程立即操作UI时,为什么没有CalledFromWrongThreadException?
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout.xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.aronho.testfragment.MainActivity">
<FrameLayout
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
view_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFF00">
<TextView
android:text="testString"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
我知道当我这个代码将抛出CalledFromWrongThreadException启动应用程序:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view=vi.inflate(R.layout.view_test,null);
final FrameLayout parentView=(FrameLayout) findViewById(R.id.myView);
parentView.addView(view);
new Thread(new Runnable(){
@Override
public void run() {
try{
Thread.sleep(3000);
}catch (Exception e){
}
parentView.removeView(view);
}
}).start();
}
}
但是当我删除了Thread.sleep(3000);,如:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view=vi.inflate(R.layout.view_test,null);
final FrameLayout parentView=(FrameLayout) findViewById(R.id.myView);
parentView.addView(view);
new Thread(new Runnable(){
@Override
public void run() {
parentView.removeView(view);
}
}).start();
}
}
应用程序不扔CalledFromWrongThreadException尽管我尝试删除使用一个新的线程的视图。为什么会发生?
也'parentView.post(() - > parentView.removeView(V));'应该工作(如果需要延迟,就像'parentView#postDelayed'一样) – PPartisan