我来自iOS背景。出于某种原因,我无法弄清如何将一个视图添加到另一个视图中。
我正在以以下方式编程创建两个ImageView
:
ImageView imageView;
ImageView imageHolder;
现在,我想做这样的事情:
imageHolder.addView(imageView);
我该怎样做到这一点?我做了很多谷歌搜索,但没有任何作用。
我来自iOS背景。出于某种原因,我无法弄清如何将一个视图添加到另一个视图中。
我正在以以下方式编程创建两个ImageView
:
ImageView imageView;
ImageView imageHolder;
imageHolder.addView(imageView);
正如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);