G Sri
G Sri

Reputation: 31

Android onCreateOptionsMenu actions are not working in fragments

I know this is not new question im asking, but i tried all the solutions. Non of them worked for me: I am using ActionBarActivity. I'm calling few fragments through main activity.

MainActivity Menu code

       @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 super.onCreateOptionsMenu(menu);
}

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

I created a new menu class and placed a icon. In fragment oncreate i placed setHasOptionsMenu(true);

Also placed menu.clear();

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

}

For performing action i used following code :

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Log.d("onOptionsItemSelected","yes");
    switch (item.getItemId()) {
        case R.id.exit:
            System.exit(1);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

menu/menu_manage_products.xml

 <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"    tools:context="b2go.moshop.devblaze.moshop.view.Products.Products_Home">

<item android:id="@+id/action"
    android:icon="@drawable/exit"
    android:title="@string/exit"
    android:orderInCategory="100"
    app:showAsAction="always"/>

I also placed log message, but log was not showing. I dont know the reason why onOptionItemSelected not performing action in fragments.

Any help would be appreciated.

Upvotes: 0

Views: 334

Answers (1)

pratham kesarkar
pratham kesarkar

Reputation: 3818

Well you must not use System.exit(1)

Instead Use a finish() or

Actually it would be good Idea to call onDestroy so u can release all the Object and then call a finish Method

for fragment

fragmentTransaction.remove(yourfragment).commit()

Upvotes: 1

Related Questions