How ListView's recycling mechanism works on Android using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to show the working of ListView's recycling mechanism on Android Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒   New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   android:padding="8dp"
   tools:context=".MainActivity">
   <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:background="@color/colorPrimary"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:scrollbars="vertical" />
</LinearLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
   private lateinit var cities:ArrayList<String>
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
      recyclerView.setHasFixedSize(true)
      val layoutManager = LinearLayoutManager(applicationContext)
      recyclerView.layoutManager = layoutManager
      cities = ArrayList()
      cities.add("Mumbai")
      cities.add("Chennai")
      cities.add("Kochin")
      cities.add("Bangalore")
      cities.add("Hyderabad")
      cities.add("Amaravati")
      cities.add("Goa")
      cities.add("Trivandram")
      cities.add("Coimbatore")
      cities.add("Vellore")
      cities.add("Salem")
      cities.add("Bhubaneswar")
      cities.add("Cuttack")
      cities.add("Mysore")
      val adapter = DataAdapter(cities)
      recyclerView.adapter = adapter
      recyclerView.addOnItemTouchListener(object: RecyclerView.OnItemTouchListener {
         var gestureDetector = GestureDetector(applicationContext, object:GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapUp(e:MotionEvent):Boolean {
               return true
            }
         })
         override fun onInterceptTouchEvent(rv:RecyclerView, e:MotionEvent):Boolean {
            val child = rv.findChildViewUnder(e.x, e.y)
            if (child != null && gestureDetector.onTouchEvent(e)){
               val position = rv.getChildAdapterPosition(child)
               Toast.makeText(applicationContext, cities[position], Toast.LENGTH_SHORT).show()
            }
            return false
         }
         override fun onTouchEvent(rv:RecyclerView, e:MotionEvent) {}
            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept:Boolean) {}
         })
      }
}

Step 4 − Create a new Kotlin class DataAdapter.kt and add the following code

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.util.ArrayList
class DataAdapter(countries: ArrayList<*>) : RecyclerView.Adapter<DataAdapter.ViewHolder>() {
   private val cities: ArrayList<*> = countries
   override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): DataAdapter.ViewHolder {
      val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.card_row, viewGroup, false)
return ViewHolder(view)
   }
   override fun onBindViewHolder(viewHolder: DataAdapter.ViewHolder, i: Int) {
      viewHolder.tvCountry.text = cities[i] as CharSequence?
   }
   inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
      val tvCountry: TextView = view.findViewById(R.id.tvCountry) as TextView
   }
   override fun getItemCount(): Int {
      return cities.size
   }
}

Step 5 − Create a layout resource file row.xml and add the following code

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/card"
   android:orientation="vertical"
   android:background="@color/colorPrimaryDark"
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
   <TextView
      android:id="@+id/tvCountry"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:layout_marginBottom="10dp"
      android:textColor="@android:color/background_dark"
      android:textSize="18sp"
      android:textStyle="bold" />
</androidx.cardview.widget.CardView>

Step 6 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon Play from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

Click here to download the project code.

raja
Published on 26-Sep-2020 15:05:15
Advertisements