问题描述
我有一个片段,可以在其中调用ActivityCompat.invalidateOptionsMenu(getActivity());
,并且在活动和片段这两个方面都成功调用了onCreateOptionsMenu()
方法.
I have a fragment where I can call ActivityCompat.invalidateOptionsMenu(getActivity());
and the method onCreateOptionsMenu()
is successfully called on both: Activity and Fragment.
但是,当我使用以下命令在片段上方添加片段时:
However, when I add a fragment on top of the fragment with:
transaction.add(R.id.fragment_home, fragment2, "fragment_ID");
transaction.addToBackStack(null);
transaction.commit();
,然后再关闭它(通过backPress或getSupportFragmentManager().popBackStack();
),ActivityCompat.invalidateOptionsMenu(getActivity());
将变得无响应.完全没有调用onCreateOptionsMenu()
.
and later close it (either by backPress or by getSupportFragmentManager().popBackStack();
), ActivityCompat.invalidateOptionsMenu(getActivity());
becomes unresponsive. onCreateOptionsMenu()
is not called at all.
我肯定知道,如果我使用replace()
而不是add()
,它将起作用,但是,由于某些原因,我需要使用add()
.
I know for sure, that it will work if I use replace()
instead of add()
, however, for some reasons, I need to use add()
.
关于活动:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
if (fragment != null)
fragment.onCreateOptionsMenu(menu, getMenuInflater());
return true;
}
关于片段1:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d(TAG, "onCreateOptionsMenu() called with: ...");
// additional code
super.onCreateOptionsMenu(menu, inflater);
}
推荐答案
请尝试以下代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
if (fragment != null) {
fragment.onCreateOptionsMenu(menu, getMenuInflater());
return true;
}
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
这篇关于在片段添加&之后,不会调用onCreateOptionsMenu.消除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!