سؤال

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.

هل كانت مفيدة؟

المحلول

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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top