我知道从工作线程访问UI视图是非法的。例如,下面的代码在Android 4.4 (API 19)
上引发异常:android.view.ViewRootImpl$CalledFromWrongThreadException
:只有创建视图层次结构的原始线程才能触摸其视图。
但是,它可以在Android 8.0 (API 26)
上正常运行,并且可以成功更新TextView
。
问题是-为什么?
也许可以在新的Android版本中从另一个线程访问视图?
public class TestActivity extends AppCompatActivity {
private Button btnStart;
private TextView txtInfo;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
txtInfo = (TextView) findViewById(R.id.txtInfo);
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread t = new Thread(new Runnable() {
@Override public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
txtInfo.setText(String.valueOf(i + 1));
}
}
});
t.start();
}
});
}
}
答案 0 :(得分:0)
来自the post
<块引用>@Override
public final void invalidateChild(View child, final Rect dirty) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null && attachInfo.mHardwareAccelerated) {
// HW accelerated fast path
onDescendantInvalidated(child, child); // <-- does not have thread check
return;
}
// A bunch of code here for old slow path
parent.invalidateChildInParent(location, dirty); // <-- has thread check
}
后来修复了:https://android-review.googlesource.com/c/platform/frameworks/base/+/937477