MainActivity.kt
package com.example.jetpack
import android.app.Activity
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// make the text view clickable
materialTextView.apply {
isClickable = true
isFocusable = true
}
applySelectableItemBackground(materialTextView)
}
}
// extension function to apply selectable item background
fun Activity.applySelectableItemBackground(v:View){
val typedValue = TypedValue()
this.theme.resolveAttribute(
android.R.attr.selectableItemBackground,
typedValue,
true
)
if (typedValue.resourceId != 0) {
v.setBackgroundResource(typedValue.resourceId)
} else {
v.setBackgroundColor(typedValue.data)
}
}
activity_main.xml
<?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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/materialTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:padding="24dp"
android:textAppearance=
"@style/TextAppearance.MaterialComponents.Headline5"
android:text="Material Text View"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjP53DeePA_4seXBoyASfXI71tgIhKe70DjpLdEJY4QgdnE5rVhrd0uj14xlkTXbomKdjvCt22UODuSwfw6hvHh4WobWmGYKCzbyYfHHZ2FH-wZTiINnCYS7Ap7rD0sQl7KloXTsYud3cKK/s1600/AndroidKotlinSelectableItemBackgroundProgrammatically.png)
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin4UTH1HLT_aU3C2PayAp-Lz5pBdxtAc6JhFVTt8qAg60gFu0z6tA6hbFghUyquYaGvmnYC9mjyvDlnQoLClxP7z6XAFrB8Dfaz_bAI3lel9HWBkMpIS2wd6Qm7j25qJlSEb-EZlb0d06Y/s1600/AndroidKotlinSelectableItemBackgroundProgrammatically2.png)