ImageView and ImageButton are used in Android application to place an image in the view. ImageButton is used to use an image as a button in your android application.
ImageView
is used to show any picture on the user interface.
Following are some of the main attributes that are most commonly used:
Attribute | Description |
---|---|
android:maxHeight | Used to specify a maximum height for this view. |
android:maxWidth | Used to specify a maximum width for this view. |
android:src | Sets a drawable as the content for this ImageView. |
android:scaleType | Controls how the image should be resized or moved to match the size of the ImageView. |
android:tint | Tints the color of the image in the ImageView. |
Therefore, any image that we want to display in the app should be placed under the drawable folder. This folder can be found under app → res → drawable. To insert an image, simply copy the image and then right click on drawable → Paste.
Following is the code which we need to add into the layout XML file to add an ImageView to our app screen.
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
Following are some of the commonly used attributes:
android:background
: This property gives a background color to your ImageView. When your image is not able to entirely fill the ImageView, then background color is used to fill the area not covered by the image.android:padding
: To provide padding or extra space inside the ImageView for the image.scaleType
in ImageViewHere we have specified all the possible values for the attribute scaleType
which can be used in your app for ImageView:
ImageButton
has the same property as ImageView
. Only one feature is extra, which is, images set through ImageButton are clickable, and actions can be attached with them upon clicking.
Here is how you define an ImageButton in the layout XML file:
<ImageButton
android:id="@+id/imgButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
Just like a button, the setOnClickListener()
can be used to set an event listener for click event on this.
imageButton = (ImageButton)findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do anything here
}
});