如何在片段生命周期中仅一次调用onCreateOptionsMenu

时间:2019-05-14 17:40:33

标签: android android-fragments android-menu

每次onCreateOptionsMenu恢复时都会调用

Fragment。创建片段后,是否有解决方案可仅调用onCreateOptionsMenu once

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_menu, menu);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint(getString(R.string.search_hint));
        searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                showContacts();
                return true;
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

它已连接到生命周期,因此将调用该方法。这并不意味着您的代码需要每次都被调用。设置一个类级别的布尔值以确保代码仅运行一次。或检查'getOnActionExpandListener'...

if(searchItem.getOnActionExpandListener() == null) {
    searchItem.setOnActionExpandListener.......
}