
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Highlight Selected Items on Android RecyclerView Using Kotlin
This example demonstrates how to properly highlight selected items on Android RecyclerView using 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"?> <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" android:padding="4dp" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="8dp" /> </RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val recyclerView: RecyclerView = findViewById(R.id.recyclerView) recyclerView.addItemDecoration(SimpleItemDecoration(this)) val layoutManager = LinearLayoutManager(this@MainActivity) recyclerView.layoutManager = layoutManager val posts = returnListItems() val adapter = RecyclerViewAdapter(this@MainActivity, posts) recyclerView.adapter = adapter } private fun returnListItems(): List<ItemObject>? { val items: MutableList<ItemObject> = ArrayList() items.add(ItemObject("Ballon'd'or", "2007", "Ricardo KaKa")) items.add(ItemObject("Ballon'd'or", "2008", "Cristiano Ronaldo")) items.add(ItemObject("Ballon'd'or", "2009 - 2012, 2015", "Lionel Messi")) items.add(ItemObject("Ballon'd'or", "2013, 2014, 2016, 2017", "Cristiano Ronaldo")) items.add(ItemObject("Ballon'd'or", "2018", "Luca Modric")) items.add(ItemObject("Ballon'd'or", "2019", "Lionel Messi")) return items } }
Step 4 − Create kotlin class files as mentioned below and add the respective codes
ItemObject.kt −
internal class ItemObject(val awardTitle: String, val awardYear: String, val player: String) { }
RecyclerViewAdapter.kt −
import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.NonNull import androidx.recyclerview.widget.RecyclerView class RecyclerViewAdapter internal constructor( context: MainActivity, private val itemList: List<ItemObject>? ) : RecyclerView.Adapter<RecyclerViewHolders>() { @NonNull override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolders { val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, null) return RecyclerViewHolders(layoutView) } override fun onBindViewHolder(holder: RecyclerViewHolders, position: Int) { holder.awardTitle.text = "Award Title: " + itemList!![position].awardTitle holder.awardYear.text = "Award Year: " + itemList[position].awardYear holder.player.text = "Player Name: " + itemList[position].player } override fun getItemCount(): Int { return this.itemList!!.size } }
RecyclerViewHolders.kt −
import android.util.SparseBooleanArray import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView.ViewHolder class RecyclerViewHolders(itemView: View) : ViewHolder(itemView), View.OnClickListener { var awardTitle: TextView var awardYear: TextView var player: TextView private val selectedItems = SparseBooleanArray() override fun onClick(view: View) { if (selectedItems[adapterPosition, false]) { selectedItems.delete(adapterPosition) view.isSelected = false } else { selectedItems.put(adapterPosition, true) view.isSelected = true } } init { itemView.setOnClickListener(this) awardTitle = itemView.findViewById(R.id.awardTitle) awardYear = itemView.findViewById(R.id.awardYear) player = itemView.findViewById(R.id.playerName) } }
SimpleItemDecoration.kt −
import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import androidx.annotation.NonNull import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView internal class SimpleItemDecoration(context: Context) : RecyclerView.ItemDecoration() { private val drawable: Drawable = ContextCompat.getDrawable(context, R.drawable.line_divider)!! override fun onDrawOver( @NonNull canvas: Canvas, parent: RecyclerView, @NonNull state: RecyclerView.State ) { val left = parent.paddingLeft val right = parent.width - parent.paddingRight val childCount = parent.childCount for (i in 0 until childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + drawable.intrinsicHeight drawable.setBounds(left, top, right, bottom) drawable.draw(canvas) } } }
Step 5 − Create drawable resource files as mentioned below and add the respective codes
background_selecter.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/holo_green_light" android:state_pressed="false" android:state_selected="true" /> <item android:drawable="@android:color/holo_purple" android:state_selected="false" /> </selector>
line_divider.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:width="2dp" android:height="2dp" /> <solid android:color="@color/colorPrimaryDark" /> </shape>
Step 6 − Create a layout resource file (list_layout.xml) and add the following code
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background_selector" android:padding="16dp"> <TextView android:id="@+id/awardTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="New Text" android:textColor="@android:color/background_dark" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/awardYear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/awardTitle" android:layout_alignStart="@+id/awardTitle" android:layout_marginTop="20dp" android:text="New Text" android:textColor="@android:color/background_dark" /> <TextView android:layout_marginBottom="10dp" android:id="@+id/playerName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:text="New Text" android:textColor="@android:color/background_dark" /> </RelativeLayout>
Step 7 − Add the following code to androidManifest.xmlv
<?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 from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen