How to Set selected item in BottomNavigationView
Instead of selected you need to setChecked(true)
that item. Try this code
mBottomNavigationView=(BottomNavigationView)findViewById(R.id.bottom_nav);
mBottomNavigationView.getMenu().findItem(R.id.item_id).setChecked(true);
Checked item is highlighted in BottomNavigationView
.
FYI: for fragment, onCreateView
BottomNavigationView mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
mBottomNavigationView.setSelectedItemId(R.id.your_item);
Kotlin Solution
In a Fragment
getActivity()?.myNavigationViewId?.selectedItemId = R.id.other_tab_id
In an Activity
myNavigationViewId?.selectedItemId = R.id.other_tab_id
NOTE: Make sure to replace
myNavigationViewId
andother_tab_id
with your actual navigation view and tab ids.
Just share my working source code
In Xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:background="@color/colorWhite"
android:id="@+id/gfPrlBnvBtmView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_alignParentBottom="true"
app:menu="@menu/bottom_navigation_main" />
</LinearLayout>
In Java,
public class TestActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener
{
private BottomNavigationView mBtmView;
private int mMenuId;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.test);
mBtmView = (BottomNavigationView) findViewById(R.id.gfPrlBnvBtmView);
mBtmView.setOnNavigationItemSelectedListener(this);
mBtmView.getMenu().findItem(R.id.action_yoga).setChecked(true);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// uncheck the other items.
mMenuId = item.getItemId();
for (int i = 0; i < mBtmView.getMenu().size(); i++) {
MenuItem menuItem = mBtmView.getMenu().getItem(i);
boolean isChecked = menuItem.getItemId() == item.getItemId();
menuItem.setChecked(isChecked);
}
switch (item.getItemId()) {
case R.id.action_food: {
}
break;
case R.id.action_medical: {
}
break;
case R.id.action_yoga: {
}
break;
case R.id.action_postures: {
}
break;
}
return true;
}
}