The widget that is used to display images is called ImageView. Just like TextView is the base class for all text based widgets, ImageView is the base for all iamge related components.
The source of the image used in this class can differ. The class has a few methods used for loading images. Those are - setImageResource(), setImageURI() and setImageBitmap(). They are used for loading images based on their resource ids, URI adresses and bitmap data respectively.
Using layout XML file you can provide the source using the android:src attribute.
The class also provides a number of methods for setting size of the image - setMaxHeight(), setMaxWidth(), getMinimumHeight(), getMinimumWidth(); as well as its scaling - getScaleType(), setScaleType().
Let's create a simple example of displaying an image.
In the earlier versions of Android SDK there was a folder called "drawable" where all the graphic files would be located. The current version generates 4 folders instead of 1 - drawable-hdpi, drawable-ldpi, drawable-mdpi and drawable-xhdpi. We currently have an icon png file in all of these folders, which are the images of our application icon. The difference is their size. To display the image roughly the same size physically, you need to create differently sized images and put them in the according density folders.
That is recommended, but not necessary. In this example, I will only put a picture snowflake.png into the drawable-hdpi folder. If an image for the needed screen density is not available, the closest one is picked and scaled automatically.
After placing the image in the folder, we can go to activity_main.xml and create a simple application that displays the image:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ImageView android:contentDescription="@string/img_alt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/snowflake"/> </LinearLayout>
You can see that I use the @drawable/snowflake value as the source. I don't need to specify the extension of the image.
The contentDescription attribute is similar to alt attribute in HTML. Set it in the strings.xml file:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Code For Food Test</string> <string name="img_alt">Snowflake</string> <string name="menu_settings">Settings</string> </resources>
And that's it!
Thanks for reading!