Display image grid in RecyclerView in Kotlin Android

We have this tutorial for Java here: Display image grid in RecyclerView in Android. And now this tutorial is for Kotlin specially.

First of all if you are doing Kotlin first time in Android Studio then checkout this tutorial here: https://developer.android.com/kotlin/get-started

We use RecyclerView for this tutorial using GridLayoutManager.

Images Grid in Android
Images Grid in Kotlin Android

First of all we will create layout for this post.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".ImageGridKotlinActivity">

  <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

  </androidx.recyclerview.widget.RecyclerView>

</androidx.constraintlayout.widget.ConstraintLayout>

Now we create adapter which holds the ImageView which will go in the grid.

class ImageGridKotlinAdapter(private val c: Context, private val images: ArrayList<String>) :
        RecyclerView.Adapter<ImageGridKotlinAdapter.ColorViewHolder>() {


  override fun getItemCount(): Int {
    return images.size
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorViewHolder {
    return ColorViewHolder(LayoutInflater.from(c).inflate(R.layout.item_grid_kotlin, parent, false))
  }

  override fun onBindViewHolder(holder: ColorViewHolder, position: Int) {
    val path = images[position]

    Picasso.get()
      .load(path)
      .resize(250, 250)
      .centerCrop()
      .into(holder.iv)

    holder.iv.setOnClickListener {
      //handle click event on image
    }
  }

  class ColorViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val iv = view.iv as ImageView
  }
}

Here I used Picasso library to display image, if you want to integrate it in your project then please check their web page: http://square.github.io/picasso/

Now we will go for the layout we used in above adapter. It just hold single ImageView.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <ImageView
    android:id="@+id/iv"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here we use the ratio constraint on the ImageView and so that we can eliminate the use of custom square image view here. It is one of the benefit of using ConstraintLayout.

Now we set the above adapter to the RecyclerView so that our Images will be displayed in the grid manner. Here we use images from Flickr public domain. In RecyclerView, we used StaggeredGridLayoutManager which tell the RecyclerView to use the grid like layout with the number of columns provided.

val sglm = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
rv.layoutManager = sglm

val imageList = ArrayList<String>()
imageList.add("https://farm5.staticflickr.com/4403/36538794702_83fd8b63b7_c.jpg")
imageList.add("https://farm5.staticflickr.com/4354/35684440714_434610d1d6_c.jpg")
imageList.add("https://farm5.staticflickr.com/4301/35690634410_f5d0e312cb_c.jpg")
imageList.add("https://farm4.staticflickr.com/3854/32890526884_7dc068fedd_c.jpg")
imageList.add("https://farm8.staticflickr.com/7787/18143831616_a239c78056_c.jpg")
imageList.add("https://farm9.staticflickr.com/8745/16657401480_57653ac8b0_c.jpg")
imageList.add("https://farm3.staticflickr.com/2917/14144166232_44613c53c7_c.jpg")
imageList.add("https://farm8.staticflickr.com/7453/13960410788_3dd02b7a02_c.jpg")
imageList.add("https://farm1.staticflickr.com/920/29297133218_de38a7e4c8_c.jpg")
imageList.add("https://farm2.staticflickr.com/1788/42989123072_6720c9608d_c.jpg")
imageList.add("https://farm1.staticflickr.com/888/29062858008_89851766c9_c.jpg")
imageList.add("https://farm2.staticflickr.com/1731/27940806257_8067196b41_c.jpg")
imageList.add("https://farm1.staticflickr.com/884/42745897912_ff65398e38_c.jpg")
imageList.add("https://farm2.staticflickr.com/1829/27971893037_1858467f9a_c.jpg")
imageList.add("https://farm2.staticflickr.com/1822/41996470025_414452d7a0_c.jpg")
imageList.add("https://farm2.staticflickr.com/1793/42937679651_3094ebb2b9_c.jpg")
imageList.add("https://farm1.staticflickr.com/892/42078661914_b940d96992_c.jpg")
val igka = ImageGridKotlinAdapter(this, imageList)
rv.adapter = igka

Here we used AndroidX which is major improvement over the Android Support Library. You can find out more information here: https://developer.android.com/jetpack/androidx

I also introduced ConstraintLayout for the first time in this project repo. Here we eliminated the SquareImageView class that we used in Java Image GridAdapter because of ratio constraint of ConstraintLayout.

You can find the source code for this on my github repo: https://github.com/dakshbhatt21/a-computer-engineer

Please let me know if you find any issue in the above code or have any difficulty in implementing that.

Display image grid in RecyclerView in Android

Display image grid in Android is now very easy to do with this tutorial. We use RecyclerView for this tutorial using GridLayoutManager.

For Kotlin tutorial for image grid in recyclerview, go here. Display image grid in RecyclerView in Kotlin Android

Images Grid in Android
Images Grid in Android

For displaying image grid in RecyclerView in Kotlin, go here: https://acomputerengineer.wordpress.com/2019/05/09/display-image-grid-in-recyclerview-in-kotlin-android/

First of all we will create layout for this post.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
  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=".ImageGridActivity">

  <android.support.v7.widget.RecyclerView 
    android:id="@+id/rv" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

  </android.support.v7.widget.RecyclerView>

</RelativeLayout>

Now we create adapter which holds the ImageView which will go in the grid.

public class ImageGridAdapter extends RecyclerView.Adapter<ImageGridAdapter.GridItemViewHolder> {

  private List<String> imageList;

  private Context c;

  public class GridItemViewHolder extends RecyclerView.ViewHolder {
    SquareImageView siv;

    public GridItemViewHolder(View view) {
      super(view);
      siv = view.findViewById(R.id.siv);
    }
  }

  public ImageGridAdapter(Context c, List imageList) {
    this.c = c;
    this.imageList = imageList;
  }

  @Override
  public GridItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_grid, parent, false);

    return new GridItemViewHolder(itemView);
  }

  @Override
  public void onBindViewHolder(GridItemViewHolder holder, int position) {
    final String path = imageList.get(position);

    Picasso.get()
        .load(path)
        .resize(250, 250)
        .centerCrop()
        .into(holder.siv);

    holder.siv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //handle click event on image
        }
    });
  }

  @Override
  public int getItemCount() {
    return imageList.size();
  }

}

Here I used Picasso library to display image, if you want to integrate it in your project then please check their web page: http://square.github.io/picasso/

Now we will go for the layout we used in above adapter. It just hold single ImageView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent">

  <com.acomputerengineer.CustomView.SquareImageView 
    android:id="@+id/siv" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" />

</RelativeLayout>

In above code, you must be thinking what is SquareImageView, right? It is the custom view which keeps ImageView square in the grid. The code for it is given below.

public class SquareImageView extends AppCompatImageView {
  public SquareImageView(Context context) {
    super(context);
  }

  public SquareImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = getMeasuredWidth();
    setMeasuredDimension(width, width);
  }
}

Now we set the above adapter to the RecyclerView so that our Images will be displayed in the grid manner. Here we use images from Flickr public domain. In RecyclerView, we used StaggeredGridLayoutManager which tell the RecyclerView to use the grid like layout with the number of columns provided.

RecyclerView rv = findViewById(R.id.rv);

StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
rv.setLayoutManager(sglm);

List<String> imageList = new ArrayList<>();
imageList.add("https://farm5.staticflickr.com/4403/36538794702_83fd8b63b7_c.jpg");
imageList.add("https://farm5.staticflickr.com/4354/35684440714_434610d1d6_c.jpg");
imageList.add("https://farm5.staticflickr.com/4301/35690634410_f5d0e312cb_c.jpg");
imageList.add("https://farm4.staticflickr.com/3854/32890526884_7dc068fedd_c.jpg");
imageList.add("https://farm8.staticflickr.com/7787/18143831616_a239c78056_c.jpg");
imageList.add("https://farm9.staticflickr.com/8745/16657401480_57653ac8b0_c.jpg");
imageList.add("https://farm3.staticflickr.com/2917/14144166232_44613c53c7_c.jpg");
imageList.add("https://farm8.staticflickr.com/7453/13960410788_3dd02b7a02_c.jpg");
imageList.add("https://farm1.staticflickr.com/920/29297133218_de38a7e4c8_c.jpg");
imageList.add("https://farm2.staticflickr.com/1788/42989123072_6720c9608d_c.jpg");
imageList.add("https://farm1.staticflickr.com/888/29062858008_89851766c9_c.jpg");
imageList.add("https://farm2.staticflickr.com/1731/27940806257_8067196b41_c.jpg");
imageList.add("https://farm1.staticflickr.com/884/42745897912_ff65398e38_c.jpg");
imageList.add("https://farm2.staticflickr.com/1829/27971893037_1858467f9a_c.jpg");
imageList.add("https://farm2.staticflickr.com/1822/41996470025_414452d7a0_c.jpg");
imageList.add("https://farm2.staticflickr.com/1793/42937679651_3094ebb2b9_c.jpg");
imageList.add("https://farm1.staticflickr.com/892/42078661914_b940d96992_c.jpg");
ImageGridAdapter iga = new ImageGridAdapter(ImageGridActivity.this, imageList);
rv.setAdapter(iga);

You can find the source code for this on my github repo: https://github.com/dakshbhatt21/a-computer-engineer

Please let me know if you find any issue in the above code or have any difficulty in implementing that.