使用android espresso,如何访问第二个活动的视图?

时间:2016-06-09 17:33:50

标签: android automated-tests android-espresso

我从LoginActivity开始,登录后,我的应用程序通过RecyclerView转到下一个Activity。我需要参考Recycler View。我这样做但是 null

RecyclerView recyclerView = (RecyclerView) loginActivity.getActivity().findViewById(R.id.messages_list);

它为null,因为loginActivity不包含RecyclerView。所以,我的问题是,一旦我转到第二个活动,我怎么能告诉espresso用新活动替换loginActivity以便我可以这样做

  RecyclerView recyclerView = (RecyclerView) currentActivity.getActivity().findViewById(R.id.messages_list);

如果不可能,还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

Activity currentActivity;

public Activity getActivityInstance() {

    getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
            if (resumedActivities.iterator().hasNext()) {
                currentActivity = (Activity) resumedActivities.iterator().next();
            }
        }
    });

    return currentActivity;
}

RecyclerView recyclerView = (RecyclerView) getActivityInstance().findViewById(R.id.messages_list);