Search code examples
androidandroid-gallery

adding an ImageView to linearlayout throws target exception


Hello all

I have an array of ImageViews which are images I take with the camera. but not saved on the sd or anything.

then I display all images in a gallery.

now I'm trying to create a preview of an image in that gallery. So an onclick of an image in the gallery will switch view and add the image to the linearlayout like so:

private void ShowImagePreview (ImageView p_image, View p_view)
{
    setContentView(R.layout.preview);
    LinearLayout prevHolder = (LinearLayout) findViewById(R.id.mainHolder);

    p_image.setLayoutParams( new ViewGroup.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,                                    WindowManager.LayoutParams.MATCH_PARENT));
    p_image.setScaleType(ImageView.ScaleType.FIT_XY);


    prevHolder.addView(p_image);
}

but on this command: prevHolder.addView(p_image); i get a target exception.

I debugged and I see that p_image is in fact not null or anything like that...

I also tried:

ImageView test = new ImageView(this);
    test.setImageResource(R.drawable.logo);
    test.setLayoutParams( new ViewGroup.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, 
                        WindowManager.LayoutParams.MATCH_PARENT));

    prevHolder.addView(test);

and this one worked.

what can be the problem?..

thank you

edit:

this is the exception i get : 05-22 17:58:25.835: ERROR/AndroidRuntime(11815): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

I understand that this is because the image is already used in the gallery. so how do i solve that?.

thank you


Solution

  • I think you can fix it, by passing Drawable to your method instead of ImageView, then create local ImageView variable and use setImageDrawable(Drawable drawable) method - after that you should be able to add ImageView to your LinearLayout - prevHolder.