Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a subview to an ImageView in Android

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.

like image 359
wiseindy Avatar asked Oct 28 '13 19:10

wiseindy


1 Answers

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);
like image 121
Adam S Avatar answered Sep 30 '22 10:09

Adam S