1 package test.utils; 2 3 import android.support.test.espresso.PerformException; 4 import android.support.test.espresso.ViewAction; 5 import android.support.test.espresso.action.CoordinatesProvider; 6 import android.support.test.espresso.action.GeneralSwipeAction; 7 import android.support.test.espresso.action.Press; 8 import android.support.test.espresso.action.Swipe; 9 import android.support.test.espresso.util.HumanReadables;10 import android.view.View;11 import android.widget.SeekBar;12 13 import static android.support.test.espresso.action.ViewActions.actionWithAssertions;14 15 /**16 * Created by qiantao on 17-10-19.17 */18 19 public class SeekBarActions {20 public static ViewAction scrubSeekBarAction(int progress) {21 return actionWithAssertions(new GeneralSwipeAction(22 Swipe.SLOW,23 new SeekBarThumbCoordinatesProvider(-1),24 new SeekBarThumbCoordinatesProvider(progress),25 Press.PINPOINT));26 }27 28 /**29 * -1 表示起始位置30 */31 private static class SeekBarThumbCoordinatesProvider implements CoordinatesProvider {32 int mProgress;33 34 public SeekBarThumbCoordinatesProvider(int progress) {35 mProgress = progress;36 }37 38 private static float[] getVisibleLeftTop(View view) {39 final int[] xy = new int[2];40 view.getLocationOnScreen(xy);41 return new float[]{(float) xy[0], (float) xy[1]};42 }43 44 @Override45 public float[] calculateCoordinates(View view) {46 if (!(view instanceof SeekBar)) {47 throw new PerformException.Builder()48 .withViewDescription(HumanReadables.describe(view))49 .withCause(new RuntimeException(String.format("SeekBar expected"))).build();50 }51 SeekBar seekBar = (SeekBar) view;52 int width = seekBar.getWidth() - seekBar.getPaddingLeft() - seekBar.getPaddingRight();53 LogUtils.i("seekBar.getProgress():" + seekBar.getProgress());54 double progress = mProgress == -1 ? seekBar.getProgress() : (mProgress * seekBar.getMax() / 100);55 int xPosition = (int) (seekBar.getPaddingLeft() + (width * progress / seekBar.getMax()));56 float[] xy = getVisibleLeftTop(seekBar);57 return new float[]{xy[0] + xPosition, xy[1]};58 }59 }60 }
检查Mtacher
public static MatcherwithSeekBarProgress(final int expectedProgress) { return new BoundedMatcher (SeekBar.class) { @Override public void describeTo(Description description) { description.appendText("expected: "); description.appendText("" + expectedProgress); } @Override public boolean matchesSafely(SeekBar seekBar) { LogUtils.i("seekBar.getProgress():" + seekBar.getProgress()); return seekBar.getProgress()*100/seekBar.getMax() == expectedProgress; } }; }
用法
for (int i = 0; i <= 100; i += 50) { onView(seekBarViewMatcher).perform(SeekBarActions.scrubSeekBarAction(i)); onView(seekBarViewMatcher).check(matches(withSeekBarProgress(i)));}