Search code examples
androidimageviewandroid-jetpack-composeandroid-selector

Can Jetpack Compose Icon load a Selector XML?


I have an imageview, which uses Selector

    <ImageView
        android:id="@+id/image_view"
        android:src="@drawable/ic_back_hand_24_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Where the selector is choosing between 2 vector drawable images depending on the state

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_baseline_back_hand_24" android:state_selected="true" />
    <item android:drawable="@drawable/ic_outline_back_hand_24" />
</selector>

This is very handy, that we can swap the image, by programmatically set the state to True or False

theImageView.setOnClickListener {
    this.isSelected = !this.isSelected
}

However, if I put it on the Jetpack Compose Icon as below

Icon(painterResource(id = R.drawable.ic_baseline_back_hand_24), contentDescription = "")

It crashes stating

java.lang.IllegalArgumentException: Only VectorDrawables and rasterized asset types are supported ex. PNG, JPG

Is there no way for Jetpack Compose Icon to load a Selector XML?


Solution

  • You can use something different to change how components appear in different states.

    For example:

    var selected by remember { mutableStateOf(false) }
    val drawableResource = if (selected) R.drawable.xxx else R.drawable.xxx
    
    Image(
        painter = painterResource(id = drawableResource),
        contentDescription = "contentDescription",
        modifier = Modifier.clickable { selected = !selected }
    )