Click by bounds / coordinates

前端 未结 3 648
清酒与你
清酒与你 2020-12-06 04:11

I know it is possible for Espresso to click by bounds the way UiAutomator does. (x and y coordinates) I have read through the documentation but I can\'t seem to find it. Any

3条回答
  •  遥遥无期
    2020-12-06 04:52

    @haffax's answer is great and works well.

    However, if you want to click in a certain part of a View that may change from screen to screen, it might be useful to click based on percents (or ratios) as even the dp numbers may not be stable across all screens. So, I made an easy modification to it:

        public static ViewAction clickPercent(final float pctX, final float pctY){
        return new GeneralClickAction(
                Tap.SINGLE,
                new CoordinatesProvider() {
                    @Override
                    public float[] calculateCoordinates(View view) {
    
                        final int[] screenPos = new int[2];
                        view.getLocationOnScreen(screenPos);
                        int w = view.getWidth();
                        int h = view.getHeight();
    
                        float x = w * pctX;
                        float y = h * pctY;
    
                        final float screenX = screenPos[0] + x;
                        final float screenY = screenPos[1] + y;
                        float[] coordinates = {screenX, screenY};
    
                        return coordinates;
                    }
                },
                Press.FINGER);
    }
    

    I thought I would share it here so others can benefit.

提交回复
热议问题