我遇到一个问题,试图在我的setUp()
方法中更改UI。
public class DrawerRootActivityTest extends android.test.ActivityInstrumentationTestCase2<DrawerRootActivity> {
@UiThreadTest
@Override
protected void setUp() throws Exception {
super.setUp();
rootActivity = (DrawerRootActivity) getActivity();
cf = rootActivity.calculatorFragment;
cf.changeDigitDisplay(2); // Line 29
}
}
这是测试控制台:
Running tests
Test running started
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:853)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
at android.view.View.invalidate(View.java:10935)
at android.view.View.invalidate(View.java:10890)
...
com.mydomain.myapp.DrawerRootActivityTest.setUp(DrawerRootActivityTest.java:29)
我需要在
setUp()
方法中对我的应用程序进行一些更改,以触发将更新用户界面的副作用。我以为添加@UiThreadTest批注会使它在主ui线程上运行。我是否应该以其他方式进行此操作?
最佳答案
尝试这个:
protected void setUp() throws Exception {
super.setUp();
rootActivity = (DrawerRootActivity) getActivity();
rootActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
cf = rootActivity.calculatorFragment;
cf.changeDigitDisplay(2); // Line 29
}
});
}