ImageView without xml definition

I want to create a dynamic number of ImageViews in Android. But to display these ImageViews I have to create them in main.xml (am I right?) Is there a way to display ImageViews without creating them in main.xml?

+4
source share
2 answers

You can create them dynamically as follows:

ImageView image=new ImageView(this); 

and to set the image in this dynamically created view, use:

 image.setImageResource(R.drawable.yourimage); 
+1
source

Put the image my_image.jpg in res/drawable/my_image.jpg and use:

 import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ImageView imageView = new ImageView(this); imageView.setImageResource(R.drawable.my_image); setContentView(imageView); } } 

Tested on Android 22 with the default template generated by android create project [...] .

0
source

Source: https://habr.com/ru/post/1399656/


All Articles