android有时菜单不显示

时间:2015-08-21 06:53:11

标签: android android-fragments menu

我在消息片段中使用选项菜单,我可以在菜单中添加好友。我可以从活动或片段导航到这个片段。当我启动此消息片段时,菜单工作正常。当我通过其他屏幕导航并来到消息片段菜单消失。在应用程序中使用/导航4-5分钟后,菜单开始随机运行。

奇怪的是,当我从活动中启动消息片段时,菜单始终运行良好。当我从片段中启动它时,这会随机出现。

这是我的代码

    public class MessagesFragment extends BaseFragment{
private static final String TAG = MessagesFragment.class.getSimpleName();
Context mContext;
View mView;
private ListView listBuddy;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    mContext = activity;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    ((InnerActivity)getActivity()).setActionbarTitle(getResources().getString(R.string.my_buddies));

    View v = inflater.inflate(R.layout.fragment_messages, container, false);
    listBuddy = (ListView) v.findViewById(R.id.listViewFindBuddy);
    this.mView = v;
    return v;
}

@Override
public void onDetach() {
    // TODO Auto-generated method stub
    super.onDetach();
}

@Override
public void onPause() {
    super.onPause();
}


@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
}

@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    // TODO Auto-generated method stub
    super.setUserVisibleHint(isVisibleToUser);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.messages, menu);
}

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_add:

        break;
    }
    return super.onOptionsItemSelected(item);
}

活动

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    return super.onPrepareOptionsMenu(menu);
}

1 个答案:

答案 0 :(得分:0)

在您的活动中添加以下代码:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}