只要测试在同一活动中运行,接受的答案就有效。但是,如果测试导航到另一个活动,则将返回错误的活动(第一个活动)。为了解决这个问题,可以创建一个返回实际活动的帮助器方法:activityTestRule.getActivity()
public Activity getCurrentActivity() {
final Activity[] currentActivity = new Activity[1];
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
Collection<Activity> allActivities = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(Stage.RESUMED);
if (!allActivities.isEmpty()) {
currentActivity[0] = allActivities.iterator().next();
}
}
});
return currentActivity[0];
}
然后它可以用作以下内容:
Activity currentActivity = getCurrentActivity();
if (currentActivity != null) {
currentActivity.findViewById(R.id.viewId);
}