I have ,
- Two fragments (Fragment1,Fragment2).
- Two buttons (Btn1 in frag1 , Btn2 in frag2).
- A bottom navigation view.
On clicking the Btn in frag1 , we will be directed to frag2.
On clicking the Btn in frag2 , we will be directed to frag1.
while directing from frag(1->2 or 2->1), the icon on the bottom navigation view stays the same
Is there a way to highlight that icon with respect to the loaded fragment?
On Click Listener for btn in frag1
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment2()).commit();
On Click Listener for btn in frag2
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment1()).commit();
OnItemSelectedListener for bottom nav in MainActivity Code
((BottomNavigationView)findViewById(R.id.bottom_nav)).setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
Fragment clickedFragment = null;
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.one: clickedFragment = new Fragment1(); break;
case R.id.two: clickedFragment = new Fragment2(); break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, clickedFragment).commit();
return true;
}
});
3
Answers
Create a class temp in the same package as the main activity is in and add the below field to it.
Just go through the code, I explained in comments.
Main Activity Code
3.OnViewCreated in Fragment1
4.OnViewCreated in Fragment2
The
setOnItemSelectedListener
is only triggered whenever the selected item of the BottomNavigationView changes. What you are currently doing is changing the current displayed fragment. Instead of changing the fragment, you should set the selected item of the BottomNavigationView instead. Something like this should workJust make sure that the setOnItemSelectedListener has a return value of true
It works fine without setting the setSelectedItemId