如何在Android中将一个子视图添加到ImageView?

7

我来自iOS背景。出于某种原因,我无法弄清如何将一个视图添加到另一个视图中。

我正在以以下方式编程创建两个ImageView

ImageView imageView;
ImageView imageHolder;

现在,我想做这样的事情:
imageHolder.addView(imageView);

我该怎样做到这一点?我做了很多谷歌搜索,但没有任何作用。

你能更抽象地描述一下你想要实现什么吗?比如说“我想在一个大图的左下角放置一个小图”,这样我们就可以建议你去哪里寻找;不幸的是,在Android中将一个ImageView添加到另一个ImageView中并没有太多意义。 - Adam S
是的,就像那样。我想要一个更大的图像作为背景,并在其上放置一个较小的图像作为前景。在iOS中很简单。但是我不知道怎么在Android中实现。 - wiseindy
3
只有ViewGroup及其子类才能通过addView方法添加子View。 - pskink
1个回答

12

正如pskink所说的那样,你只能在继承自ViewGroup的控件上通过编程方式添加视图。例如,你可以添加到LinearLayout中:

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

不过这可能对你的情况没什么帮助。要在另一张图片上方放置一张图片,您可以使用相对布局。一般情况下,您需要在 XML 布局文件中设置:

<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>

如果您事先不知道图像是什么,可以在代码中指定它们:

((ImageView)findViewById(R.id.backgroundImage)).setImageResource(R.drawable.someBackgroundImage);

我会使用RelativeLayout,因为控制相对位置更容易。 - Simon
确实,如果那不太清楚,我很抱歉。如果喜欢的话,您也可以在代码中添加到RelativeLayout。 - Adam S
嗨,亚当,非常感谢。对于Android方面,我的概念相当薄弱。在看了你的帖子后,我进行了相当多的阅读。现在我终于明白了。谢谢 :) - wiseindy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接