滑动期间无法更新ViewPager中的菜单项状态

时间:2019-10-11 21:42:00

标签: android kotlin android-viewpager androidimageslider

我的菜单和ViewPager中都有“我的收藏”图标。当我单击该项目时,它会更改。但是当我刷卡时,它不记得物品的状态。

我已经实现了setOnPageChangeListener,并在onPageSelected中检查了物品的状态并更改了可绘制对象。

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)
                }

            }

这里是项目点击

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
        }

1 个答案:

答案 0 :(得分:0)

更改图标后,您可能需要致电invalidateOptionsMenu()