Jared Price
Jared Price

Reputation: 5375

Adding items to ActionBar in a Fragment

I'm trying to figure out how to add items to the ActionBar menu through a Fragment. My application's MainActivity is inheriting ActionBarActivity and I want to be able to change the items on the ActionBar based on which Fragment is currently showing.

public class LoginFragment : BaseFragment
{
    //...

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetHasOptionsMenu(true);
        // this.Activity.MenuInflater.Inflate(Resource.Menu.something, ???);
    }
}

Upvotes: 0

Views: 411

Answers (1)

Danial Hussain
Danial Hussain

Reputation: 2530

Copied From here

   1. Remove or comment any onOptionsItemSelected() ,onMenuItemSelected() even onPrepareOptionMenu() and leave in Activity onCreateOptionsMenu() only:

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.layout.menu, menu);
    return true;
    }
  1. In Fragment class, in onCreateView(), put:

    setHasOptionsMenu(true);
    
  2. In Fragment class add :

    @Override
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     super.onCreateOptionsMenu(menu,inflater);      
     }
    
    @Override
     public boolean onOptionsItemSelected(MenuItem item){           
             switch(item.getItemId()){
             case R.id.action_insert:
                //doing stuff
             return true;
             }
             return false;
         }
    

Tested and worked on Android 4.4

Upvotes: 1

Related Questions