我試圖在動態添加視圖到另一個視圖在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