Reputation: 1143
In my application, I have an activity that loads an image into an ImageView positioned in the center of the screen. The image is first scaled to fit on the screen, and then after the bitmap of the ImageView is set, the ImageView is then resized to the same size as the Bitmap.
ImageView imageView = (ImageView) galleryActivity.findViewById(R.id.selectedImage);
Bitmap image = fileList.get(displayedImageIndex).loadScaledImage();
imageView.setImageBitmap(image);
imageView.getLayoutParams().width = image.getWidth();
imageView.getLayoutParams().height = image.getHeight();
imageView.requestLayout();
The problem is, after the ImageView is resized, it is no longer centered in the middle of the screen, it is aligned to the top of its parent. I tried both imageView.setY and imageView.setTranslationY to try and move it back to the center, but neither of those re-positioned the View. Is there any way to keep the ImageView aligned in the center of the parent after it is resized?
Here is the layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/AppTheme"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/selectedImage"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleActionBar" />
</RelativeLayout>
Upvotes: 0
Views: 466
Reputation: 2020
ImageView imageView = (ImageView)
galleryActivity.findViewById(R.id.selectedImage);
Bitmap image = fileList.get(displayedImageIndex).loadScaledImage();
imageView.setImageBitmap(image);
int cxScreen; // you must fill it
int cyScreen; // this to
int cxImg = imageView.getWidth(); // change image to imageView
int cyImg = imageView.getHeight(); // as up
LayoutParams lp = new LayoutParams(cxImg, cyImg);
lp.leftMargin = (cxScreen-cxImg)/2;
lp.topMargin = (cyScreen-cyImg)/2; // change something to cyScreen
imageView.setLayoutParams(lp);
EDIT change 3 lines
Log.i("TAG", "cxS:"+cxScreen.toString()+", cyS:"+cyScreen.toString());
Log.i("TAG", "image:"+imageView.toString());
Log.i("TAG", "parent:"+(imageView.getParent()).toString());
Upvotes: 1