Kevin Klute Kevin Klute - 1 year ago 48
Android Question

Is there a good way to consistently position a TextView on an ImageView?

I have an

, which is intended to take up the whole screen if it matters, and I intend to put several labels on it with
s. I need these labels to correspond to a precise position on the image.

I tried setting the margins in xml, but that won't work because the
won't convert between devices. I am aware that I can set positions as a percentage of the screen size programatically but this poses a few problems:

  1. I don't want to solve this problem programatically.

  2. The aspect ratio of the image is being maintained, so on most screens there will be a little bit of white space given that the screen is a different shape from the image. Also, the app is not full screen, so the notification bar takes up space. This white space and the notification bar's space makes a percentage of the screen different from a percentage of the image.

    How can i position
    's on an
    in such a way that they will be in exactly the same spot (relative to the image) on every device?

Answer Source

I ended up figuring it out myself:

text.setX((int) (img.getX()+(img.getWidth()*pct)/100)

and the same for y, where text is the TextView, img is the ImageView, and pct is the location as a percentage of the image. Another problem is that this can't be called in onCreate(). I called it in onWindowFocusChanged().

To prevent your ImageView from being a different shape from the Image, which would break this solution, you can do:


and be sure to set at least one of the dimensions as wrap_content.