是否允许从 SherlockFragment.onCreateView 调用 SherlockFragmentActivity.supportInvalidateOptionsMenu?我找不到任何其他说法,但似乎这样做可能会导致在退出活动之前无法处理对菜单项的点击。(这发生在 API 8 模拟器上)。
我对这种行为有一个相当简单的复制。出于某种原因,它仅在活动未添加任何菜单项时发生,但片段添加了。
以下是repro的代码,如果有人感兴趣的话。将会发生的是,背景不会变红。但是,如果您注释掉 getSherlockActivity().supportInvalidateOptionsMenu(),它会变成红色。
public class MainActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag_container);
FunFragment frag = new FunFragment();
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.frag_container, frag, "foobar");
trans.commit();
}
}
public class FunFragment extends SherlockFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getSherlockActivity().supportInvalidateOptionsMenu();
return new View(getActivity());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(0, 5, 0, "Do magic").setIcon(R.drawable.ic_launcher)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 5:
getView().setBackgroundDrawable(new ColorDrawable(0xFFFF0000));
return true;
default:
return false;
}
}
}