0

Currently, My goal is to place some images in an arrangement relative to the center of the screen. There is a varying number of images and locations, so I'd like to do this programmatically.

I am having trouble finding the center of the correct center of screen in terms of px. To test, I have tried placing an image at the center.

    ImageView image = (ImageView)findViewById(R.id.imageView1);

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    image.setPadding(width/2,height/2,0,0);

I understand that there is an offset since setting the padding should place the image's top left corner in the center. Even so, the image comes out as too low and too far right. What kind of issue could be causing this?

  • 1
    Instead of padding, use margin (it's the OUTER space, not the INNER space). And you have to remove half of the width and half of the height of the ImageView. You need to use a LayoutParams object: http://stackoverflow.com/a/9924812/2649012 – Phantômaxx Apr 19 '14 at 14:16
  • Actually I originally tried using margin, but I think that because I am setting the image in onCreate(), the app crashes when I load the activity. How should I use margin? – user3488606 Apr 19 '14 at 14:36
  • Did you follow the link I provided? – Phantômaxx Apr 19 '14 at 17:36

1 Answers1

0

Padding set just the inner space between element's border and content. If element have also margins, they summarized. You can use only margins (paddings equals to 0) or only paddings (margins equals to 0). Also if you not interested in supporting android 2.3 and less, you can use setX() and setY() methods of View class. I hope this help you.

user3390963
  • 2,313
  • 1
  • 13
  • 12
  • Using setX() and setY() worked with the same results. My image is still too low. Is it possible that the height does not include the actionbar and drop down menu? – user3488606 Apr 19 '14 at 14:42
  • If you're not working in full screen you have to cut away the title bar + the status bar heights. – Phantômaxx Apr 19 '14 at 17:37