Marc Romaní
Marc Romaní

Reputation: 126

Why doesn't the imageView get centered?

I know how to center the imageView using the gravity attribute of its layoutParams. However, I'm trying to get it centered playing with its margins. If the image has width w and the display window has width W my guess is that leftMargin = rightMargin = W/2 - w/2. Similarly, topMargin = bottomMargin = H/2 - h/2. The result is the imageView is centered horizontally but no vertically. Here's the code:

    // new layout, blue background
    FrameLayout root = new FrameLayout(this);
    root.setBackgroundColor(getResources().getColor(R.color.blue));

    // window dimensions
    Point window = new Point();
    getWindowManager().getDefaultDisplay().getSize(window);

    // imageView with bitmap
    ImageView img = new ImageView(this);
    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.square);
    img.setImageBitmap(bm);

    // imageView layout params
    int w = bm.getWidth();
    int h = bm.getHeight();
    FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(w, h);
    p.setMargins(window.x/2 - w/2, window.y/2 - h/2, window.x/2 - w/2, window.y/2 - h/2);
    img.setLayoutParams(p);

    // add image to root layout
    root.addView(img);

    // set layout as main layout
    setContentView(root);

If the status bar and the title bar are hidden then the image gets centered, so I guess there's something with the display window size.

Upvotes: 0

Views: 53

Answers (1)

Colin
Colin

Reputation: 569

Your problem is that you are getting the size of the entire device screen, which includes all of the pixels displaying the notification and title bar (the reason why your view was centered horizontally and not vertically). To fix this, you should grab the height of your root view rather than the device screen, then your method of centering will work.

To get the size of your root view, you can use the code from this post

Upvotes: 1

Related Questions