I have favourite icon in my menu and the ViewPager
. When I click to item, it changes. But when I swiping, It does not remember the state of item.
I have implemented setOnPageChangeListener
and in onPageSelected
checked the state of item and changed drawables.
override fun onPageSelected(position: Int) {
currentPage = position
if (imageModelArrayList!![currentPage].isFavourite == true) {
isExistInFavorite = true
menuItem?.icon =
ContextCompat.getDrawable(
applicationContext,
R.drawable.ic_favorite_black_24dp
)
helper.updateGreetingByID(true, id)
} else {
isExistInFavorite = false
menuItem?.icon =
ContextCompat.getDrawable(
applicationContext,
R.drawable.ic_favorite_border_black_24dp
)
helper.updateGreetingByID(false, id)
}
}
Here is item click
R.id.action_favorite -> {
if (!isExistInFavorite) {
greetingModel.id?.let { helper.updateGreetingByID(true, id) }
menuItem?.icon =
ContextCompat.getDrawable(this, R.drawable.ic_favorite_black_24dp)
Toast.makeText(
this@ImageDetailActivity,
"Favourite added",
Toast.LENGTH_SHORT
).show()
isExistInFavorite = true
} else {
isExistInFavorite = false
menuItem?.icon =
ContextCompat.getDrawable(this, R.drawable.ic_favorite_border_black_24dp)
Toast.makeText(
this@ImageDetailActivity,
"favourite deleted",
Toast.LENGTH_SHORT
).show()
greetingModel.id?.let { helper.updateGreetingByID(false, id) }
}
return true
}