I have a bottom navigation view. I would like to open an activity, not a fragment when clicking on action.item3. This is the code so far:
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = HomeFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = SpotsSearch1Fragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = ItemThreeFragment.newInstance();
break;
case R.id.action_item4:
selectedFragment = ItemFourFragment.newInstance();
break;
case R.id.action_item5:
selectedFragment = ItemFiveFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
I have tried to change the action at case R.id.action_item3: like this:
Intent intent = new Intent(HomeActivity.this,ChatActivity.class);
startActivity(intent);
break;
But obviously I am getting an exception at line:
transaction.replace(R.id.frame_layout, selectedFragment);
Is there a way to open an activity instead a fragment using bottom navigation vie?
Try this way
You can break
the switch()
case at your R.id.action_item3
using return true;
SAMPLE CODE
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = HomeFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = SpotsSearch1Fragment.newInstance();
break;
case R.id.action_item3:
Intent intent = new Intent(HomeActivity.this,ChatActivity.class);
startActivity(intent);
return true;
case R.id.action_item4:
selectedFragment = ItemFourFragment.newInstance();
break;
case R.id.action_item5:
selectedFragment = ItemFiveFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});