将导航视图上的项目设置为从片段中选择

Set item on navigation view as selected from 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();


        }
    });

在此之后,导航视图将错误的项目突出显示。 请帮忙

NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id./*id of nav bar*/);
 navigationView.setCheckedItem(R.id./*id of menu item to be highlighted*/);

将此代码放在 onClick 方法中或所需片段的开头

您的代码应如下所示

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*/);
    }
});