The function showActionMenu()
shows a popup menu, it works well.
I hope to change the title of a menu item when the menu is popup.
I try to add onPrepareOptionsMenu(menu: Menu)
in the code, but it doesn't work, how can I fix it?
Code A
private fun showActionMenu() {
val view = mActivity.findViewById<View>(R.id.menuMoreAction) ?: return
PopupMenu(mContext, view).run {
menuInflater.inflate(R.menu.menu_option_action, menu)
/*
onPrepareOptionsMenu(menu: Menu) {
for (item in menu){
if (item.itemId == R.id.menuMoreActionSelectAll){
item.title = "My new title"
}
}
}
*/
setOnMenuItemClickListener {
when (it.itemId) {
R.id.menuMoreActionSelectAll -> {
mHomeViewModel.setSelectStatus(ESelect.SelectAll)
}
...
}
true
}
show()
}
}
You call show()
immediately, so the menu is being shown immediately. Therefore you don't need any onPrepareOptionsMenu()
call - just run that code immediately after your call to inflate()
:
PopupMenu(mContext, view).run {
menuInflater.inflate(R.menu.menu_option_action, menu)
for (item in menu){
if (item.itemId == R.id.menuMoreActionSelectAll){
item.title = "My new title"
}
}
setOnMenuItemClickListener {
when (it.itemId) {
R.id.menuMoreActionSelectAll -> {
mHomeViewModel.setSelectStatus(ESelect.SelectAll)
}
...
}
true
}
show()
}
Of course, if you're always setting the title
of R.id.menuMoreActionSelectAll
, you should just set that title in your R.menu.menu_option_action
and skip your 'prepare' work entirely.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.