I show an ImageView in my Fragments to swipe between images. Thanks to this post I could adapt the image and the imageView to the width and height of the original image. But if the image always will be on the left top corner. Then I changed the layout of the fragment, tried to center the imageView horizontally and vertically. But after surrounding it with a RelativeLayout or a LinearLayout, I got a IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Not working code in comments:
Fragment:
ImageView image;
Bitmap bitmap = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
image = (ImageView) (ImageView) inflater.inflate(R.layout.fragment_image_page, container, false);
// ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_image_page, container, false);
// image = (ImageView) rootView.findViewById(R.id.imageView);
new ImageLoad().execute("");
return image;
}
private class ImageLoad extends AsyncTask<String, Void, Boolean>
{
int width;
int height;
@Override
protected Boolean doInBackground(String... params)
{
URL url;
try
{
url = new URL(
"http://www.....jpg");
// !!! ERROR IN FOLLOWING LINE !!!
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
width = bitmap.getWidth();
height = bitmap.getHeight();
int bounding = getResources().getDisplayMetrics().widthPixels;
if (bounding < width)
{
float ratio = width / height;
width = bounding;
height = (int) (width / ratio);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
}
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Boolean doInBackground)
{
FrameLayout.LayoutParams param = (FrameLayout.LayoutParams) image.getLayoutParams();
param.width = width;
param.height = height;
image.setLayoutParams(param);
image.setImageBitmap(bitmap);
}
}
XML working:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="BILD" />
XML not working:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="BILD" />
</RelativeLayout>