Android ImageView, ImageButton Using Kotlin

Filed Under: Android

In this tutorial, we’ll be discussing and implementing ImageView and ImageButton in our android application.

Android ImageView

ImageView is a subclass of the View class in Android. It is used to display images onto the screen.
The images can be of the form of bitmap or a drawable resource file.
The basic syntax for an ImageView is :


<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sample_1" />

The android:src attribute is used to set a drawable resource file.
android:background is used to set the background of the ImageView.
android:scaleType is used to set the cropping/fitting style of the image.
These are the primary attributes of an ImageView.

To create an ImageView programmatically, we use :


val imageView = ImageView(this)

this represents the context in which the ImageView is visible. It can be activity/fragment.
To set a drawable on an ImageView programmatically we use:

imageView.setImageResource(R.drawable.drawable_id)

Android ImageButton

An ImageButton is a subclass of an ImageView. It’s a Button + ImageView. An ImageButton cannot hold text.
All the attributes above, defined for the ImageView are applicable on an ImageButton too.
Just like Buttons, on an ImageButton we can set the OnClickListener as well as the OnLongClickListener.

For an in-depth view of the XML attributes of the ImageView and ImageButton refer to the JournalDev Android ImageView, ImageButton Tutorial.

Multiple Densities

Screen density is different for different phones and sizes. A drawable file applicable for a screen size of 4.5 inches can get blurred when seen on a screen size of 5.5 or 6 inches. Hence in order to keep the image intact for all kinds of devices, we can create different drawable folders.
drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdpi are created for low, medium, high, extra high, extra extra high densities. Running an application on the device, the Android SDK automatically detects the screen size and density and uses the appropriate image resource files from the drawable folder.

Generating Image Files for each of these Densities

We can use Android Asset Studio to create image resources for different densities.
Alternatively, install the Android Drawable Importer plugin in Android Studio from the Preferences -> Plugins.
android-imageview-kotlin-drawable-plugin
To create images for all densities goto drawable | Batch Drawable and import the image.

android-imageview-kotlin-drawable-chooser

android-imageview-kotlin-drawable-image-select

Set the density type for the current image and drawables for all the densities would be generated for the file.

Project Structure

We’ve added three sample images and using Drawable Importer created files for each drawable density.

android-imageview-kotlin-project-structure

Code

The code for the activity_main.xml class is given below.


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/sample_1" />


    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:src="@android:drawable/ic_menu_set_as"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_height="wrap_content" />


</FrameLayout>

We’ve used a FrameLayout in which the ImageView occupies the complete screen and the ImageButton is set at the bottom of the layout.

The code for the MainActivity.kt Kotlin class is given below:


package net.androidly.androidiyimageviewsbuttons

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {


    val sampleDrawables = intArrayOf(R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3)

    var i = 0

    val scaleType = arrayListOf(ImageView.ScaleType.CENTER_CROP, ImageView.ScaleType.FIT_CENTER, ImageView.ScaleType.CENTER_CROP, ImageView.ScaleType.FIT_XY)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        imageView.setOnClickListener(this)
        imageButton.setOnClickListener(this)
    }

    override fun onClick(p0: View?) {
        when (p0) {
            is ImageButton -> if (i == sampleDrawables.size) {
                i = 0
                imageView.setImageResource(sampleDrawables[i])
                imageView.colorFilter = null
                i++
            } else {
                imageView.setImageResource(sampleDrawables[i])
                imageView.colorFilter = null

                i++
            }
            is ImageView -> {
                imageView.setColorFilter(ContextCompat.getColor(this, R.color.myColor))
                imageView.scaleType = scaleType.shuffled().take(1)[0]
            }


            else -> Toast.makeText(applicationContext, "Neither ImageView nor ImageButton", Toast.LENGTH_LONG).show()
        }
    }


}

In the above code, we’ve created an array of Drawables and an ArrayList of ScaleType.
We’ve implemented the View.OnClickListener on the Activity class and set the OnClickListener on both: ImageView and ImageButton.
Thanks to Kotlin Android Extensions, we don’t need to use findViewById to hook the XML ids in our Kotlin Activity.
We’ve used a when statement wherein we check the type of the View that’s clicked to trigger the action.
The ImageButton case must be kept above ImageView since every ImageButton is an ImageView. If it was kept below, the ImageButton click listener would have triggered the ImageView block in the when statement.
On ImageButton click, we set the next drawable on the ImageView from the array.
On ImageView click, we set the color filter over the ImageView using the colorFilter setter property. Also, we set a random scaleType on the ImageView from the arrayList by shuffling the array and taking the first element.

The output of the above application in action is given below.

android-kotlin-imageview-image-button-output

The scaleType changes when the ImageView is clicked.

This brings an end to this tutorial. You can download the AndroidlyImageViewsButtons Project fro the link below. To reduce the download size, we’ve removed the xxhdpi, xhdpi image resource files. Try building them using the Drawable Importer Plugin!

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages