0% found this document useful (0 votes)
39 views

Generics Array

Generics allow defining classes, methods and properties that can work with different data types while maintaining compile-time type safety. A generic class is defined using angle brackets <> to specify type parameters. The document discusses generic classes in Kotlin, how to create instances specifying type arguments, and advantages like avoiding type casting and ensuring type safety at compile time. It also covers generic arrays represented by Array<T> and how to create, access and modify array elements. The document concludes with examples of implementing a ListView and RecyclerView in Android using Kotlin.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Generics Array

Generics allow defining classes, methods and properties that can work with different data types while maintaining compile-time type safety. A generic class is defined using angle brackets <> to specify type parameters. The document discusses generic classes in Kotlin, how to create instances specifying type arguments, and advantages like avoiding type casting and ensuring type safety at compile time. It also covers generic arrays represented by Array<T> and how to create, access and modify array elements. The document concludes with examples of implementing a ListView and RecyclerView in Android using Kotlin.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Generics are the powerful features that allow us to define classes, methods and properties which are

accessible using different data types while keeping a check of the compile-time type safety. Creating
parameterized classes – A generic type is a class or method that is parameterized over types. We
always use angle brackets <> to specify the type parameter in the program. Generic class is defined as
follows:

class MyClass<T>(text: T) {
var name = text
}

To create an instance of such a class, we need to provide the type arguments:

val my : MyClass<String> = Myclass<String>("HELLO")

If the parameters can be inferred from the arguments of constructor, one is allowed to omit the type
arguments:

val my = MyClass("HELLO")

Here, HELLO has type String, so the compiler figures out that we are talking about Myclass<String>

Advantages of generic –

1. Type casting is evitable- No need to typecast the object.


2. Type safety- Generic allows only single type of object at a time.
3. Compile time safety- Generics code is checked at compile time for the parameterized type so
that it avoids run time error.

Generic Arrays
Generic arrays in Kotlin are represented by Array<T>.

To create an empty array, use emptyArray<T>() factory function:

val empty = emptyArray<String>()

To create an array with given size and initial values, use the constructor:

var strings = Array<String>(size = 5, init = { index -> "Item #$index" })


print(Arrays.toString(a)) // prints "[Item #0, Item #1, Item #2, Item #3, Item #4]"
print(a.size) // prints 5

Arrays have get(index: Int): T and set(index: Int, value: T) functions:

strings.set(2, "ChangedItem")
print(strings.get(2)) // prints "ChangedItem"

// You can use subscription as well:


strings[2] = "ChangedItem"
print(strings[2]) // prints "ChangedItem"
Android ListView in Kotlin
Android ListView is a ViewGroup which is used to display the list of items in multiple rows and
contains an adapter which automatically inserts the items into the list.

The main purpose of the adapter is to fetch data from an array or database and insert each item that
placed into the list for the desired result. So, it is main source to pull data from strings.xml file which
contains all the required strings in Kotlin or xml files.

Android Adapter

Adapter holds the data fetched from an array and iterates through each item in data set and generates
the respective views for each item of the list. So, we can say it act as an intermediate between the data
sources and adapter views such as ListView, Gridview.

Different Types of Adapter –

 ArrayAdapter: It always accepts an Array or List as input. We can store the list items in the strings.xml
file also.
 CursorAdapter: It always accepts an instance of cursor as an input means
 SimpleAdapter: It mainly accepts a static data defined in the resources like array or database.
 BaseAdapter: It is a generic implementation for all three adapter types and it can be used in the views
according to our requirements.

Now, we going to create an android application named as ListViewInKotlin using an arrayadapter.


Open an activity_main.xml file from \res\layout path and write the code like as shown below.

activity_main.xml file

In this file, we declare the LisitView within LinearLayout and set its attributes. Later, we will access
the ListView in Kotlin file using the id.

<?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:orientation="vertical">
<ListView
android:id="@+id/userlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.kt
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback
method and access the UI element form the XML using findViewById.

import android.widget.ArrayAdapter

import android.widget.ListView

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

// use arrayadapter and define an array

val arrayAdapter: ArrayAdapter<*>

val users = arrayOf(

"Virat Kohli", "Rohit Sharma", "Steve Smith",

"Kane Williamson", "Ross Taylor"

// access the listView from xml file

var mListView = findViewById<ListView>(R.id.userlist)

arrayAdapter = ArrayAdapter(this,

android.R.layout.simple_list_item_1, users)

mListView.adapter = arrayAdapter

Android RecyclerView in Kotlin


A RecyclerView is an advanced version of ListView with improved performance. When you have a
long list of items to show you can use RecyclerView. It has the ability to reuse its views. In
RecyclerView when the View goes out of the screen or not visible to the user it won’t destroy it, it will
reuse these views. This feature helps in reducing power consumption and providing more
responsiveness to the application. Now let’s see how to implement RecyclerView using Kotlin.
The following is a step by step process to display items in a RecyclerView widget.

The complete project structure with the file locations is as shown in the following screenshot.

Step 1

Create an Android project with Empty Activity. We are keeping the default values for Name and
Package name.

Choose Kotlin for the Language.


Step 2

Add RecyclerView widget to activity_main.xml. Please note the id we provided for this RecyclerView
widget.

The width and height of this RecyclerView widget match the parent.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<androidx.constraintlayout.widget.ConstraintLayout
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=".MainActivity">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3

Create a layout file item.xml. This layout file is used to display each item in the RecylcerView
widget.
Each item in the RecyclerView is displayed as a LinearLayout with a single TextView in it. Please note
the id of the TextView itemTextView. We will need this id to set this TextView’s text with the item’s
string value.

item.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="#8EAF9E">
<TextView
android:id="@+id/itemTextView"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:textColor="#000000"
android:gravity="center"
android:textSize="20sp" />
</LinearLayout>

Step 4

Create a custom Adapter that extends RecyclerView.Adapter. This adapter takes care of populating
the items in it with values.

In Custom Adaptor class, we override three methods that are responsible for creating and setting values
for the items in RecyclerView.

1. onCreateViewHolder() creates the MyViewHolder widget for each item, with the specified
item.xml layout.
2. onBindViewHolder() gets the MyViewHolder widget for each item, and the position of the item as
arguments. Using the position, we can get the item from the items list. And we can use this item (String
in this case) to update MyViewHolder widget that is displayed as item (LinearLayout with TextView) in
the RecyclerView.
3. getItemCount() sets the number of elements to be displayed in the RecyclerView. We are setting this
size with the the size of ArrayList<String> itemsList in which we are storing the strings.

CustomAdapter.kt

package com.example.myapplication

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView

internal class CustomAdapter(private var itemsList: List<String>) :


RecyclerView.Adapter<CustomAdapter.MyViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var itemTextView: TextView = view.findViewById(R.id.itemTextView)
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder
{
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val item = itemsList[position]
holder.itemTextView.text = item
}
override fun getItemCount(): Int {
return itemsList.size
}
}

Step 5

Inside MainActivity,

1. Get reference to the RecyclerView in layout file activity_main.xml. The id of the RecyclerView in layout
file is recyclerView.
2. Initialize CustomAdapter with the items List.
3. Set Layout Manager with LinearLayoutManager for the RecyclerView.
4. Set adapter with CustomAdapter for the RecyclerView.
5. Now we can prepare the items and update RecyclerView via CustomAdapter using
notifyDataSetChanged().

MainActivity.kt

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {


private val itemsList = ArrayList<String>()
private lateinit var customAdapter: CustomAdapter

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "RecyclerView - www.tutorialkart.com"

val recyclerView: RecyclerView = findViewById(R.id.recyclerView)


customAdapter = CustomAdapter(itemsList)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = customAdapter
prepareItems()
}
private fun prepareItems() {
itemsList.add("Item 1")
itemsList.add("Item 2")
itemsList.add("Item 3")
itemsList.add("Item 4")
itemsList.add("Item 5")
itemsList.add("Item 6")
itemsList.add("Item 7")
itemsList.add("Item 8")
itemsList.add("Item 9")
itemsList.add("Item 10")
itemsList.add("Item 11")
itemsList.add("Item 12")
itemsList.add("Item 13")
customAdapter.notifyDataSetChanged()
}
}

Step 6

Run this Android Application. We will get the following screen.


RecyclerView is scrollable. So, we should be able to scroll through the items in this RecyclerView.

Step 7

You may open Layout Inspector in Android Studio 4, Menu > View > Tool Windows > Layout
Inspector, and observe the items inside RecyclerView.

You might also like