7

I come from an iOS background. For some reason, I cannot figure out how to add a view to another view.

I have two ImageViews that I am creating programatically as follows:

ImageView imageView;
ImageView imageHolder;

Now, I want to do something like this:

imageHolder.addView(imageView);

How do I accomplish this? Did a lot of Googling but no use.

Azeem
  • 251
  • 5
  • 13
wiseindy
  • 19,434
  • 5
  • 27
  • 38
  • Could you describe what you're trying to achieve in a more abstract sense? Something like "I want a smaller image placed in the bottom left corner of a larger image" - we could suggest where to look for that; unfortunately adding an ImageView into another ImageView doesn't really make much sense in Android. – Adam S Oct 28 '13 at 19:35
  • Yeah, its exactly like that. I want to have a bigger image as a background and a smaller image placed ON it as the foreground. It's pretty straightforward in iOS. But cannot figure out how would I do it in Android – wiseindy Oct 28 '13 at 19:37
  • 3
    only ViewGroup and its dubclasses can have child Views added by means of addView – pskink Oct 28 '13 at 19:42

1 Answers1

12

As pskink said, you can only add views programatically to something that is a ViewGroup. You can add to a LinearLayout, for example:

LinearLayout layout = (LinearLayout)findViewById(R.id.linear_layout);
layout.addView(new EditText(context));

That probably won't help your scenario, though. To place an image on top of another you could use a Relative Layout. You'd typically set this up in the XML layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/backgroundImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/foregroundImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/backgroundImage"
        android:layout_alignLeft="@id/backgroundImage" />

</RelativeLayout>

Then you can specify the images in code if you don't know what they're going to be beforehand:

((ImageView)findViewById(R.id.backgroundImage)).setImageResource(R.drawable.someBackgroundImage);
Adam S
  • 16,144
  • 6
  • 54
  • 81
  • I would use a RelativeLayout since controlling the relative positions is easier. – Simon Oct 28 '13 at 20:35
  • Indeed, sorry if that wasn't clear. You can also add to a RelativeLayout in code if preferred. – Adam S Oct 28 '13 at 20:38
  • Hi Adam, thanks a lot. My concepts are pretty weak when it comes to Android. I did quite a good amount of reading after your post. Now it makes sense. Thanks :) – wiseindy Oct 29 '13 at 19:27