Reputation: 423
I have two Activities called 'MainActivity' and 'LibraryActivity'. These two activities are using the same 'Bottom Navigation View'. In this case I have managed to select the correct item (highlighted with a different color) when the intent calls the 'LibraryActivity'. The problem is coming back to the 'MainActivity' by using 'onBackPressed()' from 'LibraryActivity' bottom 'Navigation View' item is not highlighted with a different color.
Below is my code:
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
// used to highlight the correct item
Menu bottomMenu = bottomNavigationView.getMenu();
for (int i=0; i<bottomMenu.size(); i++)
{
MenuItem bottomMenuItem = bottomMenu.getItem(0);
bottomMenuItem.setChecked(true);
}
// item click listener
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_library:
Intent intent = new Intent(getApplicationContext(), LibraryActivity.class);
intent.putExtra("NUM", "0");
startActivity(intent);
break;
}
return true;
}
});
}
LibraryActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
context = this;
bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
// used to highlight the correct item
Menu bottomMenu = bottomNavigationView.getMenu();
for (int i=0; i<bottomMenu.size(); i++)
{
MenuItem bottomMenuItem = bottomMenu.getItem(1);
bottomMenuItem.setChecked(true);
}
// item click listener
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_for_you:
onBackPressed();
break;
return true;
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
Upvotes: 2
Views: 376
Reputation: 8851
Take this code ,
Menu bottomMenu = bottomNavigationView.getMenu();
for (int i=0; i<bottomMenu.size(); i++)
{
MenuItem bottomMenuItem = bottomMenu.getItem(0);
bottomMenuItem.setChecked(true);
}
and place it here ,
@Override
protected void onResume() {
super.onResume();
Menu bottomMenu = bottomNavigationView.getMenu();
for (int i=0; i<bottomMenu.size(); i++)
{
MenuItem bottomMenuItem = bottomMenu.getItem(0);
bottomMenuItem.setChecked(true);
}
}
So that it gets updated when it resumes after some other activity finishes and the current activity is resumed.
Upvotes: 2