override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.delete_icon) {
isSelected = !isSelected
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Toggle state on devices with API 26+
if (isSelected) {
item.iconTintList = ContextCompat.getColorStateList(this, R.color.red)
} else {
item.iconTintList = ContextCompat.getColorStateList(this, R.color.white)
}
} else {
// Toggle state on devices with API below 26
if (isSelected) {
item.icon =
ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24_red)
} else {
item.icon = ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24)
}
}
return true
}
return super.onOptionsItemSelected(item)
}
This is the way to do this. You can change the icon colour but the function to do it only works on API 26+. To make it work on below API 26, you need to change the icon altogether as there is no other way to change the colour.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.delete_icon) {
isSelected = !isSelected
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Toggle state on devices with API 26+
if (isSelected) {
item.iconTintList = ContextCompat.getColorStateList(this, R.color.red)
} else {
item.iconTintList = ContextCompat.getColorStateList(this, R.color.white)
}
} else {
// Toggle state on devices with API below 26
if (isSelected) {
item.icon =
ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24_red)
} else {
item.icon = ContextCompat.getDrawable(this, R.drawable.ic_baseline_favorite_24)
}
}
return true
}
return super.onOptionsItemSelected(item)
}
发布评论
评论(3)
这就是这样做的方法。您可以更改图标颜色,但要执行的功能仅适用于API 26+。为了使其在API 26以下的工作,您需要完全更改图标,因为没有其他方法可以更改颜色。
This is the way to do this. You can change the icon colour but the function to do it only works on API 26+. To make it work on below API 26, you need to change the icon altogether as there is no other way to change the colour.
*尝试此代码 -
*try this code -
您可以创建一个全局菜单变量,然后在
onCreateOptionsMenu()
中初始化它,然后在您的onclick()
中使用它。中
在您的
You could create a global Menu variable and initialize it in the
onCreateOptionsMenu()
and then use it in youronClick()
.In your
onCreateOptionsMenu()
In your button's
onClick()
method