我自己找到了一个解决方法,所以把它贴在这里以防万一有人需要它。这段代码对我有用:
public static void clickOnUpActionBarButton(Activity activity) {
ActionMenuItem logoNavItem = new ActionMenuItem(activity, 0, android.R.id.home, 0, 0, "");
ActionBarSherlockCompat absc = (ActionBarSherlockCompat) UiTestUtils.invokePrivateMethodWithoutParameters(
SherlockFragmentActivity.class, "getSherlock", activity);
absc.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, logoNavItem);
}
getSherlock()
首先需要通过调用SherlockFragmentActivity来获取 ActionBarSherlockCompat 对象。这个方法是受保护的,所以我使用反射 API 来调用它:
public static Object invokePrivateMethodWithoutParameters(Class<?> clazz, String methodName, Object receiver) {
Method method = null;
try {
method = clazz.getDeclaredMethod(methodName, (Class<?>[]) null);
} catch (NoSuchMethodException e) {
Log.e(TAG, e.getClass().getName() + ": " + methodName);
}
if (method != null) {
method.setAccessible(true);
try {
return method.invoke(receiver, (Object[]) null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
您需要传递solo.getCurrentActivity()
给我的clickOnUpActionBarButton(Activity activity)
方法,然后将按下向上按钮。