Iam creating a menu toolbar in MainActivity
, that have body fragment (the only toolbar is set in the activity not within the fragments)
When the default fragment is set (HomeFragment), I want to hide search
and sort
icons from the toolbar menu, else to show them in the other ContentFragment
ContentFragment
can take different toolbar names verbs, nouns, pronouns..
and HomeFragment
only Home
this is why Im using if(supportActionBar!!.title== "Home") {
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
transaction(HomeFragment)...commit()
.....
}
//below bundle ends
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
if(supportActionBar!!.title== "Home") {
menu?.findItem(R.id.db_menu_search)?.isVisible = false
menu?.findItem(R.id.db_menu_sort)?.isVisible = false
}else{
menu?.findItem(R.id.db_menu_search)?.isVisible = true
menu?.findItem(R.id.db_menu_sort)?.isVisible = true
}
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.header_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.db_menu_search -> {
Toast.makeText(applicationContext, "Search Clicked", Toast.LENGTH_SHORT)
.show()
}
R.id.db_menu_sort -> {
sortDialog()
}
R.id.header_menu_verbs -> {
getToFragmentB("Verbs",1)
}
}
return false
}
header_menu.xml
//just informative
<item id=db_menu_search icon=ic_search />
<item id=db_menu_sort icon=ic_sort />
<item id=db_menu_verbs />
<item id=db_menu_nouns /> ....
I added onPrepareOptionsMenu
method expecting to make it work...it doesnt work properly
what am doing wrong?
How can I hide those two icons from the toolbar when HomeFragment is set in the activity and show them once the another fragment is displayed?
question from:
https://stackoverflow.com/questions/66056515/show-hide-especific-items-from-toolbar-menu-not-working-kotlin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…