user3314337
user3314337

Reputation: 341

How to hide action items on Toolbar

I have replaced the Actionbar with Toolbar. My minSDK-17 and TargetSDK-21. So here is the issue. I have 2 activities and 4 action items.

All the 4 action items are maintained in toolbar_actions.xml

Currently all the 4 action items are displayed in both the activities. However, I would like to display only the action items A,B in 1st activity

I would like to display only the action items C,D in 2nd activity. How can this be achieved? I believe it doesn't make sense to have different toolbar_actions.xml file for every activity.

Or should I use the Contextual Action bar (CAB)? I believe it makes sense to use the CAB only when the action items are used for specific purpose (like highlight, copy, select in case of pdf reader app) or used rarely.

The other issue is that, I would like to add a spinner/drop-down list inside the toolbar. Can spinners in toolbar be used to switch between different activities or is the toolbar spinner restricted to fragments alone

Upvotes: 1

Views: 956

Answers (2)

Leo
Leo

Reputation: 101

A minor improvement to Dejan's solution in order to avoid NullPointerExceptions and return the actual inflation result:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    boolean result = getMenuInflater().inflate(R.menu.toolbar_actions, menu);

    MenuItem actionC = menu.findItem(R.id.C);
    if(actionC!=null)
        actionC.setVisible(false);

    return result;
}

(Sorry, I can not comment yet)

Upvotes: 0

Dejan Veternik
Dejan Veternik

Reputation: 146

  1. You can use onCreateOptionsMenu method in each activity to hide action items you want. For the 1st activity you want to display items A and B only. So you hide C and D:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_actions, menu);
    
        // Hide action items, you don't want to display 
        menu.findItem(R.id.C).setVisible(false);
        menu.findItem(R.id.D).setVisible(false);
    
        return true;
    }
    
  2. You can use toolbar with spinner to switch activities, but you will have to add it to all activities (re-use it) that you want to switch between.

Upvotes: 3

Related Questions