2

I want to create image view from code and add to layout...But l don't use in-code setup layout.I have RelativeLayout in xml and use that setContentView(R.layout.activity_game); How add imageview to layout?

4

2 回答 2

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);
于 2013-08-08T11:40:20.120 回答
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);
于 2013-08-08T12:01:07.970 回答