1

I am using Android window-manager to display an overlay image onto the users phone, but it is not setting the ImageView in the correct location, it always defaults to the center of the screen. I know the location is correct cause I have used accessibility services to touch the location and with show touches turned on in my phone it is touching the correct location. So why will the imageview not go to this location?

I get the location of the where I want to place the image from and imageview in my app:

Point centerPoint = getCenterPointOfView(myImageView);
int xImageLocation = centerPoint.x;
int yImageLocation = centerPoint.y;

And then I open the new overlay with this:

//Add the view to the window.
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            LAYOUT_FLAG,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

params.x = xImageLocation;
params.y = yImageLocation;

mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    if (mWindowManager != null) {
        mWindowManager.addView(mFloatingView, params);
    }else {
        return;
    }
user2101081
  • 445
  • 5
  • 22

1 Answers1

3

You need to set gravity of WindowManager.LayoutParams to Gravity.TOP | Gravity.LEFT.

As you've noticed by default its set to Gravity.CENTER, so with x=0 and y=0 your mFloatingView should be exactly in the middle of the screen.

Pawel
  • 15,548
  • 3
  • 36
  • 36
  • All that did was move it to the top of the screen and to the very right of the screen, it didn't center it at the X Y I have set. – user2101081 Jul 07 '18 at 17:18
  • 1
    What kind of `x` `y` are you passing to the layout, with TOPLEFT gravity and `0,0` it should make your view anchored to the very top-left of the screen. – Pawel Jul 07 '18 at 17:39
  • It does put it to the top left if I do 0,0 ... But I am not trying to do 0,0 I am trying to center it on the x, y screen coordinates I have. – user2101081 Jul 07 '18 at 19:13
  • So you have to subtract half of width and height of your view from target x and y, pretty simple. – Pawel Jul 07 '18 at 19:47