Android ImageView, ImageButton using Kotlin

Filed Under: Android

In this tutorial, we’ll discuss and implement ImageView and ImageButton in our android application using Kotlin code.

What is 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 a bitmap or a drawable resource file.

ImageView XML Code

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 primary attributes of an ImageView are as follows:

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

Creating ImageView in Kotlin Code

We can create an ImageView object in the following Kotlin code.

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)

What is Android ImageButton?

An ImageButton is a subclass of an ImageView. It’s a Button + ImageView. An ImageButton cannot hold text.

All the attributes for the ImageView are applicable to an ImageButton too.

Just like Buttons, on an ImageButton we can set the OnClickListener as well as the OnLongClickListener event.

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

Multiple Screen Densities

Screen density is different for different types of phones. 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.

The drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, and drawable-xxhdpi are created for low, medium, high, extra high, and 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.

How to Generate Image Files for Different Screen 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

Go to “drawable | Batch Drawable” and import the images to have the proper image for every screen density.

android drawable chooser

android drawable select image

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

Android ImageView ImageButton Kotlin Project

We’ve added three sample images and used Drawable Importer to create files for each drawable density.

android imageview imagebutton kotlin project structure

XML Layout 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. The ImageView occupies the complete screen and the ImageButton is set at the bottom of the layout.

Kotlin Code

The code for the MainActivity.kt Kotlin’s 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 to 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.

App Output

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

android kotlin imageview imagebutton output

The scale type changes when the ImageView is clicked.

You can download the AndroidlyImageViewsButtons Project from the following link: AndroidIyImageViewsButtons

To reduce the download size, we’ve removed the xxhdpi and 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