ListView In Android - Kotlin

Kotlin
 
In this article, we will learn how to work with ListView in Android using Kotlin. If you are new to Kotlin, read my previous articles. It is very basic but worthy of learning from scratch.
Implementing ListView in android using Kotlin is very easy and here, we will customize the adapter implementation for ListView.
 
Coding Part
 
I have split this article into 3 steps as follows.
 
Step 1 - Creating a New Android Project with Kotlin in Android Studio.
Step 2 - Adding a User Interface in your Layout file.
Step 3 - Implementing the ListView in Android Application.
 
Step 1 - Creating a New Android Project with Kotlin in Android Studio
 
By default, Android Studio 3.0 has the checkbox for Kotlin Support for your Android application. Create a new project in Android studio, check the Kotlin support, and start as usual with Android Studio 3.0. 
 
For migrating your Java Android Project to your Kotlin Android Project, you can do the following processes.
 
Kotlin
 
Configuring Kotlin
 
Kotlin support can be configured by selecting Tools - Kotlin - Configure Kotlin. Then, click “Sync Now”. This step is applicable to the Android Studio pre-versions of 3.0. The best way is you must update your Android Studio.
 
In Android Studio 3.0, by default, you have Kotlin Activity. For Android Studio with versions lower than 3.0, you can convert your Java activity into Kotlin Activity.
 
Open Quick Search or Click Ctrl + Shift + A for Windows Users and Search and Select “Convert Java to Kotlin” or simply Select Ctrl + Shift + Alt + K. 
 
Step 2 - Adding User Interface in Your Layout file
 
In this step, we will add ListView in our Layout file. Open your activity_main.xml file and paste the following.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical">  
  6.   
  7.     <ListView  
  8.         android:id="@+id/listView"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" />  
  11. </LinearLayout>  
Then create a list item for your ListView. Create a Layout file and add the following lines.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:focusable="true"  
  6.     android:paddingLeft="16dp"  
  7.     android:paddingRight="16dp"  
  8.     android:paddingTop="10dp"  
  9.     android:paddingBottom="10dp"  
  10.     android:clickable="true"  
  11.     android:background="?android:attr/selectableItemBackground"  
  12.     android:orientation="vertical">  
  13.   
  14.     <TextView  
  15.         android:id="@+id/title"  
  16.         android:textColor="@color/title"  
  17.         android:textSize="16sp"  
  18.         android:textStyle="bold"  
  19.         android:layout_alignParentTop="true"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content" />  
  22.   
  23.     <TextView  
  24.         android:id="@+id/genre"  
  25.         android:layout_below="@id/title"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content" />  
  28.   
  29.     <TextView  
  30.         android:id="@+id/year"  
  31.         android:textColor="@color/year"  
  32.         android:layout_width="wrap_content"  
  33.         android:layout_alignParentRight="true"  
  34.         android:layout_height="wrap_content" />  
  35.   
  36. </RelativeLayout>  
In the next step, we will learn how to initialize the ListView and its adapter.
 
Step 3 - Implementing the ListView in Kotlin
 
Create a Model class for your ListView. Create Movies.kt class file and add the following lines.
  1. class Movies {  
  2.     var title: String = ""  
  3.     var genre: String = ""  
  4.     var year: String = ""  
  5.   
  6.     constructor() {}  
  7.   
  8.     constructor(title: String, genre: String, year: String) {  
  9.         this.title = title  
  10.         this.genre = genre  
  11.         this.year = year  
  12.     }  
  13. }  
Now, create an adapter for your ListView and in my case, I created “MovieListViewAdapter.kt”. Then add the following code to your adapter class.
  1. class MoviesListViewAdapter(private val activity: Activity, moviesList: List) : BaseAdapter() {  
  2.   
  3.     private var moviesList = ArrayList()  
  4.   
  5.     init {  
  6.         this.moviesList = moviesList as ArrayList  
  7.     }  
  8.   
  9.     override fun getCount(): Int {  
  10.         return moviesList.size  
  11.     }  
  12.   
  13.     override fun getItem(i: Int): Any {  
  14.         return i  
  15.     }  
  16.   
  17.     override fun getItemId(i: Int): Long {  
  18.         return i.toLong()  
  19.     }  
  20.   
  21.     @SuppressLint("InflateParams""ViewHolder")  
  22.     override fun getView(i: Int, convertView: View?, viewGroup: ViewGroup): View {  
  23.         var vi: View = convertView as View  
  24.         val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater  
  25.         vi = inflater.inflate(R.layout.movie_list_row, null)  
  26.         val title = vi.findViewById(R.id.title)  
  27.         val genre = vi.findViewById(R.id.genre)  
  28.         val year = vi.findViewById(R.id.year)  
  29.         title.text = moviesList[i].title  
  30.         genre.text = moviesList[i].genre  
  31.         year.text = moviesList[i].year  
  32.         return vi  
  33.     }  
  34. }  
Here, I created a custom adapter using Base Adapter and we have inflated the layout file for our ListView Item.
 
Then create/open your activity and in my case I am opening MainActivity.kt and add the following codes.
  1. listView = findViewById(R.id.listView) as ListView  
  2. adapter = MoviesListViewAdapter(this, movieList)  
  3. (listView as ListView).adapter = adapter  
The code “findViewById(R.id.listView)” is similar to “(ListView)findViewById(R.id.listView)”
 
Full Code
 
You can find the full code implementation below.
  1. class ListViewActivity : AppCompatActivity() {  
  2.   
  3.     var listView: ListView? = null  
  4.     var movieList = ArrayList<Movies>()  
  5.     var adapter: MoviesListViewAdapter? = null  
  6.   
  7.     override fun onCreate(savedInstanceState: Bundle?) {  
  8.         super.onCreate(savedInstanceState)  
  9.         setContentView(R.layout.activity_listview)  
  10.   
  11.         listView = findViewById(R.id.listView) as ListView  
  12.   
  13.         adapter = MoviesListViewAdapter(this, movieList)  
  14.         (listView as ListView).adapter = adapter  
  15.   
  16.         prepareMovieData()  
  17.   
  18.         // Click event for single list row  
  19.         (listView as ListView).onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> Toast.makeText(applicationContext, movieList?.get(i)?.title, Toast.LENGTH_SHORT).show() }  
  20.     }  
  21.   
  22.     private fun prepareMovieData() {  
  23.         var movie = Movies("Mad Max: Fury Road""Action & Adventure""2015")  
  24.         movieList.add(movie)  
  25.   
  26.         movie = Movies("Inside Out""Animation, Kids & Family""2015")  
  27.         movieList.add(movie)  
  28.   
  29.         movie = Movies("Star Wars: Episode VII - The Force Awakens""Action""2015")  
  30.         movieList.add(movie)  
  31.   
  32.         movie = Movies("Shaun the Sheep""Animation""2015")  
  33.         movieList.add(movie)  
  34.   
  35.         movie = Movies("The Martian""Science Fiction & Fantasy""2015")  
  36.         movieList.add(movie)  
  37.   
  38.         movie = Movies("Mission: Impossible Rogue Nation""Action""2015")  
  39.         movieList.add(movie)  
  40.   
  41.         movie = Movies("Up""Animation""2009")  
  42.         movieList.add(movie)  
  43.   
  44.         movie = Movies("Star Trek""Science Fiction""2009")  
  45.         movieList.add(movie)  
  46.   
  47.         movie = Movies("The LEGO Movies""Animation""2014")  
  48.         movieList.add(movie)  
  49.   
  50.         movie = Movies("Iron Man""Action & Adventure""2008")  
  51.         movieList.add(movie)  
  52.   
  53.         movie = Movies("Aliens""Science Fiction""1986")  
  54.         movieList.add(movie)  
  55.   
  56.         movie = Movies("Chicken Run""Animation""2000")  
  57.         movieList.add(movie)  
  58.   
  59.         movie = Movies("Back to the Future""Science Fiction""1985")  
  60.         movieList.add(movie)  
  61.   
  62.         movie = Movies("Raiders of the Lost Ark""Action & Adventure""1981")  
  63.         movieList.add(movie)  
  64.   
  65.         movie = Movies("Goldfinger""Action & Adventure""1965")  
  66.         movieList.add(movie)  
  67.   
  68.         movie = Movies("Guardians of the Galaxy""Science Fiction & Fantasy""2014")  
  69.         movieList.add(movie)  
  70.   
  71.         adapter?.notifyDataSetChanged()  
  72.     }  
  73. }  
If this article is useful to you, do like and keep on commenting if you have any doubts.


Similar Articles