Forked from kotor-le-chat/OrientationChangeAction.java
Last active
August 29, 2015 14:21
-
-
Save ivngrz/439fffbe3d4ee13e034d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package net.slideshare.mobile.test.util; | |
| import android.app.Activity; | |
| import android.content.pm.ActivityInfo; | |
| import android.support.test.espresso.UiController; | |
| import android.support.test.espresso.ViewAction; | |
| import android.support.test.internal.runner.lifecycle.ActivityLifecycleMonitorRegistry; | |
| import android.support.test.runner.lifecycle.Stage; | |
| import android.view.View; | |
| import org.hamcrest.Matcher; | |
| import java.util.Collection; | |
| import static android.support.test.espresso.matcher.ViewMatchers.isRoot; | |
| /** | |
| * An Espresso ViewAction that changes the orientation of the screen | |
| */ | |
| public class OrientationChangeAction implements ViewAction { | |
| private final int orientation; | |
| private OrientationChangeAction(int orientation) { | |
| this.orientation = orientation; | |
| } | |
| @Override | |
| public Matcher<View> getConstraints() { | |
| return isRoot(); | |
| } | |
| @Override | |
| public String getDescription() { | |
| return "change orientation to " + orientation; | |
| } | |
| @Override | |
| public void perform(UiController uiController, View view) { | |
| uiController.loopMainThreadUntilIdle(); | |
| final Activity activity = findActivity(view.getContext()); | |
| if (activity == null){ | |
| throw new IllegalStateException("Could not find the current activity"); | |
| } | |
| activity.setRequestedOrientation(orientation); | |
| Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry | |
| .getInstance().getActivitiesInStage(Stage.RESUMED); | |
| if (resumedActivities.isEmpty()) { | |
| throw new RuntimeException("Could not change orientation"); | |
| } | |
| } | |
| private static Activity findActivity(Context context) { | |
| if (context == null) | |
| return null; | |
| else if (context instanceof Activity) | |
| return (Activity) context; | |
| else if (context instanceof ContextWrapper) | |
| return findActivity(((ContextWrapper) context).getBaseContext()); | |
| return null; | |
| } | |
| public static ViewAction orientationLandscape() { | |
| return new OrientationChangeAction(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); | |
| } | |
| public static ViewAction orientationPortrait() { | |
| return new OrientationChangeAction(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment