How to add a subview to an ImageView in Android
Asked Answered
E

1

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.

Erbium answered 28/10, 2013 at 19:30 Comment(3)
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.Fechner
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 AndroidErbium
only ViewGroup and its dubclasses can have child Views added by means of addViewMicrostructure
F
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);
Fechner answered 28/10, 2013 at 19:43 Comment(3)
I would use a RelativeLayout since controlling the relative positions is easier.Tactual
Indeed, sorry if that wasn't clear. You can also add to a RelativeLayout in code if preferred.Fechner
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 :)Erbium

© 2022 - 2024 — McMap. All rights reserved.