Thursday, March 12, 2020

android kotlin - selectableItemBackground programmatically

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>
More android examples