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 imageView
in 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:
@ContainerOptions(CacheImplementation.NO_CACHE)
annotation in activities which include the XMLimageView.clearFindViewByIdCache()
when navigating to Activity BNone of them worked for me.
If you know the true solution, I will be very appreciated. Thanks
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