I want to add save and cancel buttons in the action bar of my application when I am in an activity that allows inserting data to the user, in the same way as for example shows the Trello application:
I need these buttons to be shown only in a specific activity, but not in the other activities of the application. I do not know how to implement this.
Here setHomeAsUpIndicator is creating the dismiss btn and menu is creating the done btn. hope this answers the query.
Set the toolbar
<android.support.design.widget.AppBarLayout
android:id="@+id/my_appbarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="0dp"
android:theme="@style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_margin="0dp"
app:layout_scrollFlags="snap"
app:navigationIcon="@drawable/ic_dismiss_24dp"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
Set the actionbar dismiss btn
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setDisplayHomeAsUpEnabled(true);
supportActionBar.setDisplayShowHomeEnabled(true);
}
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_dismiss_24dp);
Set the functions inside your activity for menu
@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_page, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_done:
// done btn functionalities goes here
break;
case android.R.id.home:
//dismiss btn functionality goes here
break;
}
return super.onOptionsItemSelected(item);
}
Set the menu file(menu_page) inside res/menu
<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="____your context____">
<item
android:id="@+id/action_done"
android:icon="@drawable/ic_done_24dp"
android:orderInCategory="100"
android:title="@string/done"
app:showAsAction="always" />
</menu>