Material "close" button in Toolbar instead of Back

I have seen in Google's Inbox App, composing a new email, in the toolbar instead of the back button (an arrow) it has a "close" button (see picture).

How can I achieve this?

inbox compose close button

53176 次浏览

Use  

this.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_close);

 

to achieve this.

You can create your own close icon or get from material design icon set on GitHub. Also, add this line before above line to make close function as the back arrow.

this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

You can define a style:

<style name="Theme.Toolbar.Clear">
<item name="toolbarNavigationIcon">@drawable/abc_ic_clear_mtrl_alpha</item>
</style>

and use it in your theme:

<style name="Theme.Clear">
<item name="toolbarTheme">@style/Theme.Toolbar.Clear</item>
</style>

You need to define a parent in the manifest, then override onSupportNavigationUp() if using the support app bar of course. Also, go to this handy site for the icon packs: https://www.google.com/design/icons/

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.yourAwesomeLayout);


setupToolBar();
}


private void setupToolBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);


if (toolbar == null) return;


setSupportActionBar(toolbar);


getSupportActionBar().setDisplayHomeAsUpEnabled(true);


getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
}


@Override
public boolean onSupportNavigateUp() {
finish(); // close this activity as oppose to navigating up


return false;
}

enter image description here

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Search");
toolbar.setNavigationIcon(R.drawable.abc_ic_clear_mtrl_alpha);
setSupportActionBar(toolbar);

An alternative to defining the parent activity in the manifest is to handle what action to take in the onOptionsItemSelected method like in this example:

 @Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
// Respond to the action bar's Up/Home/back button
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}

sorry for late reply. i found easiest solution for you. here above all answer not works for me (because i want to use toolbar not actionBar due to theming). so try to add close button through xml layout. and it works.

here is an xml syntax to add close button to toolbar(v7) .

app:navigationIcon="@drawable/ic_close_black_24dp"

ans here is an out put image output image

You can use this function

fun setNavigationIcon(@DrawableRes resId: Int? = null) {
this.supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(resId ?: R.drawable.ic_close)
}
}