【问题标题】:How to add a subview to an ImageView in Android如何在 Android 中将子视图添加到 ImageView
【发布时间】:2013-10-28 19:30:15
【问题描述】:

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

我有两个ImageViews,我正在以编程方式创建如下:

ImageView imageView;
ImageView imageHolder;

现在,我想做这样的事情:

imageHolder.addView(imageView);

我该如何做到这一点?做了很多谷歌搜索但没有用。

【问题讨论】:

  • 您能用更抽象的方式描述您想要实现的目标吗?诸如“我想要将较小的图像放置在较大图像的左下角”之类的东西-我们可以建议在哪里寻找它;不幸的是,在 Android 中将 ImageView 添加到另一个 ImageView 并没有多大意义。
  • 是的,就是这样。我想要一个更大的图像作为背景,一个较小的图像放置在它上面作为前景。这在 iOS 中非常简单。但无法弄清楚我将如何在 Android 中做到这一点
  • 只有ViewGroup及其dubclasses可以通过addView的方式添加子View

标签: android imageview subview addsubview


【解决方案1】:

正如 pskink 所说,您只能以编程方式将视图添加到 ViewGroup。您可以添加到LinearLayout,例如:

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

不过,这可能对您的方案没有帮助。要将图像放在另一个图像之上,您可以使用Relative Layout。您通常会在 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,因为控制相对位置更容易。
  • 确实,如果不清楚,很抱歉。如果愿意,您还可以在代码中添加到 RelativeLayout。
  • 嗨,亚当,非常感谢。当涉及到 Android 时,我的概念非常薄弱。在你的帖子之后,我做了很多阅读。现在它是有道理的。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多