From the main activity I'm simply trying to change the title of an item of a "basic menu" (drawer layout, navigatonView, menu.xml, setNavigationItemSelectedListener in the activity etc..) at runtime ( minSdkVersion 23,targetSdkVersion 29).
Basically there's a variable in shared preferences referring to the "logged user" and I would like to set that string as the title of the item or restore the default item title (stored in string.xml) if the user is "disconnected".
As suggested in others Q/A like this one, for example, I'm trying to call invalidateOptionsMenu() which is supposed to trigger onPrepareOptionsMenu(), which I have overridden with my "logic".
NavigationView of the main activity
<androidx.drawerlayout.widget.DrawerLayout.....>
........
<com.google.android.material.navigation.NavigationView
android:id="@+id/main_drawer_navigationView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="@drawable/background_gradient_orange"
android:fitsSystemWindows="false"
app:itemTextColor="@android:color/white"
app:itemIconTint="@android:color/white"
app:menu="@menu/drawer_menu"
app:headerLayout="@layout/nav_header_main"/>
</androidx.drawerlayout.widget.DrawerLayout>
The only method overridden for menu
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
sharedPreferences.getString(CURRENT_EXT_USER,null)?.let {
menu?.findItem(R.id.menu_item_change_user)?.title = it
}?: kotlin.run {
menu?.findItem(R.id.menu_item_change_user)?.title = getString(R.string.item_change_user)
}
return super.onPrepareOptionsMenu(menu)
}
The problem seems that onPrepareOptionsMenu() it's never fired, not even when the activity is created or when invalidateOptionsMenu() is called.
I have tried also with: override fun onCreateOptionsMenu(menu: Menu?): Boolean { return true } but nothing happen. The only way I could make it work it's to do it "manually" with
main_drawer_navigationView.menu.findItem( R.id.menu_item_change_user).title = "user"
but I don't really like this solution