Sunday, April 12, 2020

SelectableItemBackground in Android kotlin

Another use of ?attr is to draw ripples on views when clicked. SelectableItemBackground is a predefined drawable that can be set as background to any view which needs ripple effect.

MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        materialTextView.apply {
            isClickable = true
            isFocusable = true
        }
        applySelectableItemBackground(materialTextView)
    }
}
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>

No comments:

Post a Comment