Before android 3.0, users used to press hardware menu button, to see what all actions are available for current screen.
As of android 3.0, the hardware menu button is not available on android devices and options menu is replaced by action bar.
Actionbar is a bar on top of the activity. It can provide actions and navigation using views.
We can add custom views to actionbar using setCustomView method that takes View as argument. for that first we need to enable DISPLAY_SHOW_CUSTOM option.
In this article we will see how we can create custom actionbar (save and discard actionbar).
1. first we will create custom_actionbar.xml file
2. in this layout we have defined common properties in custom styles.
3. Now in our activity we will inflate this layout and add to actionbar.
LayoutInflater inflater = LayoutInflater.from(this); View actionBarButtons = inflater.inflate(R.layout.custom_actionbar, new LinearLayout(this), false); View cancelActionView = actionBarButtons.findViewById(R.id.action_cancel); cancelActionView.setOnClickListener(mActionBarListener); View doneActionView = actionBarButtons.findViewById(R.id.action_done); doneActionView.setOnClickListener(mActionBarListener); getActionBar().setCustomView(actionBarButtons); getActionBar().setDisplayOptions( ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
a. inflate takes xml layout and gives us java object.
b. using setDisplayOptions, we can set multiple display options. like in this example.
we don’t want home as up, home and title, we only want DISPLAY_SHOW_CUSTOM.
4. handle click event of buttons.
private final View.OnClickListener mActionBarListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.action_done: onSave(); break; case R.id.action_cancel: finish(); break; } } };
5. declare activity in AndroidManifest.xml file
And here is the screen shot