工具栏菜单onOptionsItemSelected不适用于片段

问题描述 投票:0回答:1

当用户使用导航组件单击工具栏上的菜单时,我试图更改当前片段,但是我根本无法使菜单从片段上正常工作!我正在使用底部导航栏,其中包含2个片段,每个片段都有不同的工具栏菜单项,而不是使用导航抽屉。这是HomeFragment.kt的一些片段:

    override​ ​fun​ ​onCreateView​(
        ​inflater​:​ ​LayoutInflater​, ​container​:​ ​ViewGroup?​,
        ​savedInstanceState​:​ ​Bundle?​
    )​:​ ​View?​ {
        activity?.title ​=​ getString(​R​.string.title_home)
        setHasOptionsMenu(​true​)

        ​return​ inflater.inflate(​R​.layout.fragment_home, container, ​false​)
    }

    override​ ​fun​ ​onCreateOptionsMenu​(​menu​:​ ​Menu​, ​inflater​:​ ​MenuInflater​) {
        inflater.inflate(​R​.menu.toolbar_menu, menu)
        ​super​ .onCreateOptionsMenu(menu, inflater)
    }

    ​override​ ​fun​ ​onOptionsItemSelected​(​item​:​ ​MenuItem​)​:​ ​Boolean​ {
        ​when​ (item.itemId) {
            ​R​.id.toolbar_about ​-​>​ {
                activity?.findNavController(​R​.id.bottom_nav_host)?.navigate(​R​.id.toAboutFragment)
                ​Toast​.makeText(context, ​"​You clicked on About menu​"​, ​Toast​.​LENGTH_SHORT​)
            }
            ​else​ ​-​>​ ​super​.onOptionsItemSelected(item)
        }
        ​return​ ​true​
    }

它甚至不显示我指定的Toast。有人可以帮我吗?预先感谢!

android android-toolbar android-architecture-navigation
1个回答
0
投票

您可以在主持人活动上打开菜单。如果要在Fragment上打开它,则可以使用上下文。检查下面的代码。

public class FragmentEditProfile extends Fragment {
    Context m_context;      //Context

    public static FragmentEditProfile newInstance() {
        return new FragmentEditProfile();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Get context of host activity.
        m_context = getContext();
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View fragmentLayout = inflater.inflate(R.layout.fragment_profile_edit, container, false);

        // setNavigationOnClickListener of the host activity.
        ((MainActivity)m_context).toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Open the menu using context of host activity
                ((MainActivity) m_context).openDrawer();
            }
        });
        return fragmentLayout;
    }
}

[如果有任何疑问,请告诉我。希望它会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.