Using BottomNavigationView outside of MainActivity in a Fragment

How do I use the bottomNavigationView variable outside of the MainActivity?

In MainActivity, I would use this to set and reove a badge

// To Add
BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(menuItemId);
badge.setVisible(true);

// To remove
bottomNavigationView.removeBadge(menuItem.getItemId());

However it will return null in a fragment if I try the same method

public BottomNavigationView bottomNavigationView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MainActivity main = new MainActivity();
        main.bottomNavigationView.removeBadge(2131231026);

I have also tried this in the fragment, but nothing occurs

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v =  inflater.inflate(R.layout.fragment_chat, container, false);
        final View nav =  inflater.inflate(R.layout.activity_main, container, false);
        bottomNavigationView = nav.findViewById(R.id.bottomNav);
        BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(2131231026);
        badge.setVisible(false);

Answer

I don’t know if you have this in Java (requireActivity) and if you have only one Activity in your project, but It can be the solution :

(requireActivity() as MainActivity).findViewById(R.id.bottomNav)

Also you can add function in your main Activity like addBadge / removeBadge.

But I think you can’t get bottomNavigationView outside the main activity because it’s part of UI mainActivity and not others fragments PS : Your line ” MainActivity main = new MainActivity();” isn’t good because you instanciate an activity and not get actual instance so bottomNavigationView is null. May be use this.getActivity() ( this = fragment instance)

Leave a Reply

Your email address will not be published. Required fields are marked *