user3051755
user3051755

Reputation: 1557

Square ImageView in the center of the screen

I would like to position ImageView in the center of the screen and set the width and height of the ImageView to the width of the screen.

I tried this, but the width of the ImageView is not equal to the width of the screen and ImageView is positioned in the top left corner:

        DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
        imageView.setLayoutParams(layoutParams);

In xml ImageView is in the center of the screen:

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

Upvotes: 0

Views: 262

Answers (1)

Emma
Emma

Reputation: 9308

In Java code, setLayoutParams is overriding layout rules (params starting with layout_) you defined in xml. You need to add the rules to keep centering the image. Also LayoutParams will take integer in "pixels" not "dp".

So try this -

DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels;

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)dpWidth, (int)dpWidth);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(layoutParams);

Also, you might want to play with scaleType to let image fill the space. Please check here for the available scaleType. http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

Upvotes: 1

Related Questions