为了解决这个问题,我们可以使用Espresso-contrib库中的IdlingResource来等待视图加载完成。具体实现步骤如下:
androidTestImplementation 'androidx.test.espresso:espresso-contrib:'
public class ViewIdlingResource implements IdlingResource {
private final View view;
private final String name;
private volatile ResourceCallback callback;
public ViewIdlingResource(View view, String name) {
this.view = view;
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isIdleNow() {
boolean idle = !view.isShown();
if (idle && callback != null) {
callback.onTransitionToIdle();
}
return idle;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
this.callback = callback;
}
}
@Test
public void testViewLoaded() {
View view = activityRule.getActivity().findViewById(R.id.my_view);
ViewIdlingResource idlingResource = new ViewIdlingResource(view, "my_view");
Espresso.registerIdlingResources(idlingResource);
// Perform actions on the view
Espresso.unregisterIdlingResources(idlingResource);
}
通过上述步骤,我们可以使用自定义的IdlingResource来等待视图加载完成,从而解决R.id值不断变化的问题。