将imageview添加到布局

时间:2013-08-08 11:39:06

标签: android imageview relativelayout

我想从代码创建图像视图并添加到布局......但我不使用代码内设置布局。我在xml中使用RelativeLayout并使用setContentView(R.layout.activity_game); 如何将imageview添加到布局?

2 个答案:

答案 0 :(得分:7)

RelativeLayout rl = (RelativeLayout)findViewById(R.id.id_of_your_relative_layout_here);
ImageView iv = new ImageView(this)
iv.setImageResource(R.drawable.some_drawable_of_yours); //or iv.setImageDrawable(getResources().getDrawable(R.drawable.some_drawable_of_yours));
rl.addView(iv);

答案 1 :(得分:0)

XML应该是:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:id="@+id/relativeblablabla"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

...........YOUR CODE HERE............

</RelativeLayout>

代码(在onCreate中):

RelativeLayout rl = (RelativeLayout)findViewById(R.id.relativeblablabla);
ImageView imageView = new ImageView (this);
iv.setImageResource(R.drawable.YOUR_IMAGE);
rl.addView(imageView);