Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Navigation Item Selected programmatically

When I created a new project I used Navigation Drawer Activity app screen

Now each menu item when I click on it will open a fragment by calling a method name replacement.

    public boolean onNavigationItemSelected(MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_home) {
                replaceFragment(0);
                setTit = "Your State Info.";
                setTitle(setTit);
 } else if (id == R.id.nav_flashcards) {

            replaceFragment(1);
            setTit = "Flash Cards";
            setTitle(setTit);

in fragment 1 I have a RadioGroup when the checked change will open the fragmet depends on the radio checked.

 @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {

        RadioButton radioButton = (RadioButton)getActivity().findViewById(i);

            if(radioButton.getTag()==1)
        ((MainActivity) getActivity()).replaceFragment(0);
           else if ((radioButton.getTag()==2))
             ((MainActivity) getActivity()).replaceFragment(2);
    }

The App work fine , but the issue is how can I change the Navigation Item Selected and also change the title for the action bar.

it's possible to use this way

 ((MainActivity) getActivity()).onNavigationItemSelected(menuitem);

but from the fragment how can I access the the items in the menu>activity_main_drawer.xml and pass it through menuitem

like image 478
Mi_Dhah Avatar asked Jan 24 '26 05:01

Mi_Dhah


1 Answers

This works for me..

NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
        navigationView.getMenu().getItem(2).setChecked(true); 
like image 112
Mi_Dhah Avatar answered Jan 26 '26 20:01

Mi_Dhah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!