Currently I am working on an app which has a bottom navbar with three menu items. I had used setOnNavigationItemSelectedListener()
for items being clicked. but now iam facing issue that the method has been depreciated.
Java
'setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemSelectedListener)' is deprecated
Is there any way to resolve it? is is there any better alternative than setOnNavigationItemSelectedListener()
method.
Its deprecated according to github sources: BottomNavigationView.setOnNavigationItemSelectedListener
In its comment you can read:
@deprecated Use {@link NavigationBarView#setOnItemSelectedListener(OnItemSelectedListener)}
* instead.
so use NavigationBarView.setOnItemSelectedListener from its base class:
/**
* Set a listener that will be notified when a navigation item is selected. This listener will
* also be notified when the currently selected item is reselected, unless an {@link
* OnItemReselectedListener} has also been set.
*
* @param listener The listener to notify
* @see #setOnItemReselectedListener(OnItemReselectedListener)
*/
public void setOnItemSelectedListener(@Nullable OnItemSelectedListener listener) {
selectedListener = listener;
}
Also see this commit
as it explains confusion about this change:
The listeners were deprecated in favor of
NavigationBarView#OnItemSelectedListener
andNavigationBarView#OnItemReselectedListener
, but deprecation documentation was never added, so it's unclear what developers should use instead.
you can try setonItemSelectedListener
. It is working same as setOnNavigationItemSelectedListener()
[tested in android 11]
bnv.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch(id){
//check id
}
return true;
}
});
Kotlin:
bnv.setOnItemSelectedListener { item ->
when (item.itemId) {
}
true
}
We can use setOnItemSelectedListener
instead of setOnNavigationItemSelectedListener
and
setOnItemReselectedListener
instead of setOnNavigationItemReselectedListener
navView.setOnItemSelectedListener {
// do something
true
}
// In case the default menu can be the first menu
// Should set the default selected menu BETWEEN setOnItemSelectedListener and setOnItemReselectedListener.
// It will make setOnItemSelectedListener fired when you launch app.
// If you set default menu AFTER setOnItemReselectedListener.
// Then setOnItemReselectedListener will fired when you launch app
navView.selectedItemId = R.id.navigation_home
navView.setOnItemReselectedListener {
// do something
}
you can use in Kotlin
buttmNav.setOnItemSelectedListener { item ->
when (item.itemId) {
}
true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With