Search code examples
androidcachingkotlinkotlin-android-extensionssynthetic

How to prevent Kotlin from caching the state of ImageView inside an included XML layout by several fragments/activities


I have an XML layout named layout_image like this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/grumpy_cat"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

I include the XML in several activites/fragments

<include
    android:id="@+id/llytImage"
    layout="@layout/layout_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

I set a color filter on imageViewin Actitivty A by accessing it with kotlinx synthetic:

import kotlinx.android.synthetic.main.layout_image.view.*

llytImage.imageView.setColorFilter(Color.RED)

It becomes red and I navigate to Activity B. Activity B also includes the same XML layout with the same id. However, imageView is still red in Activity B.

It seems Kotlin caches the state of imageView and use the same view aiming better performance.

However, I don't want it to cache imageView. I need the default state. I tried 2 ways to prevent Kotlin from caching it:

  1. Using @ContainerOptions(CacheImplementation.NO_CACHE) annotation in activities which include the XML
  2. Calling imageView.clearFindViewByIdCache() when navigating to Activity B

None of them worked for me.

If you know the true solution, I will be very appreciated. Thanks


Solution

  • Manipulating the drawable rather than the image view by calling mutate() worked for me:

    import kotlinx.android.synthetic.main.layout_image.view.*
    
    val drawable = llytImage.imageView.drawable.mutate()
    val colorFilter = PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_IN)
    drawable.colorFilter = colorFilter