Actionbar items are duplicating

Ganesh picture Ganesh · Nov 5, 2013 · Viewed 11.7k times · Source

I have Action Bar in my application. I am adding action items using menu.xml. I am using action bar-compat as my support library. I observed a weird issue where my action items are getting duplicated.

I am finding this issue randomly when leave my device idle or work with other applications. Please find the screen shot and my code below:

private LoginWebActivity mContext;
private final String TAG = "LoginFragment";

// for metrics
private String mPageNameSignIn = "signin";

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

    return mView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mContext = (LoginWebActivity) getActivity();
    initFragment();

}

@Override
public void onResume() {

    super.onResume();
}

/**
 * Initialises the views and variables of the fragment.
 */
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
protected void initFragment() {


    mWebView = (WebView) mView.findViewById(R.id.webView);
    Bundle b = mContext.getIntent().getExtras();
    if (b != null) {
        mUrl = b.getString(Constants.EXTRA_WEB_LOGIN_URL);
    }
    super.initFragment();

    setHasOptionsMenu(true);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Navigate
    switch (item.getItemId()) {
    case R.id.menu_item_signup:
        mContext.onSignUpClick();
        break;
    case android.R.id.home:
        if (!goBack())
            getActivity().finish();
    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

My XML :

<?xml version="1.0" encoding="utf-8"?>

<item
    android:id="@+id/menu_item_signup"
    allergy:showAsAction="ifRoom"
    android:title="@string/sign_up">
</item>

enter image description here

Answer

Renan Bandeira picture Renan Bandeira · Dec 4, 2013

You must clear your menu object before adding items. I had the same problem and this was the best solution that I've found.

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