Search code examples
androidandroid-navigationview

Set item on navigation view as selected from fragment


When moving to a different fragment I want the corresponding item in the navigation menu to be highlighted. This should be done from the fragment itself. Below is the code present in the fragment:

  saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispName = dispNameET.getText().toString();
            myRef.setText(dispName);

            //going to another fragment
            Fragment fragment = new ListFragment();
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame_layout, fragment);
            fragmentTransaction.commit();


        }
    });

After this the navigation view shows wrong item as highlighted. Please help


Solution

  • Your code should look like this

    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispName = dispNameET.getText().toString();
            myRef.setText(dispName);
    
            //going to another fragment
            Fragment fragment = new ListFragment();
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame_layout, fragment);
            fragmentTransaction.commit();
            NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id./*id of nav bar*/);
            navigationView.setCheckedItem(R.id./*id of menu item to be highlighted*/);
        }
    });