Actually, it's pretty easy (although it's a bit of hacks). First, create a button to go back (preferably as a selector to distinguish the pressed / normal state:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/back_button_pressed"/> <item android:drawable="@drawable/back_button"/> </selector>
Then set the logo of the toolbar logo toolbar.setLogo(R.drawable.back_button_selector); for this image toolbar.setLogo(R.drawable.back_button_selector);
Then it remains only to install click-listener.
View logoView = getToolbarLogoIcon(toolbar); logoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); ... private View getToolbarLogoIcon(Toolbar toolbar){ //check if contentDescription previously was set boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription()); String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : "logoContentDescription"); toolbar.setLogoDescription(contentDescription); ArrayList<View> potentialViews = new ArrayList<>(); //find the view based on it content description, set programatically or with android:contentDescription toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); //Nav icon is always instantiated at this point because calling setLogoDescription ensures its existence View logoIcon = null; if (potentialViews.size() > 0) { logoIcon = potentialViews.get(0); } //Clear content description if not previously present if (hadContentDescription) { toolbar.setLogoDescription(null); } return logoIcon; }
(Thanks to Nicola post here ). Or, if you are not afraid of reflection, this is easily done as follows:
try { Field declaredField = toolbar.getClass().getDeclaredField("mLogoView"); declaredField.setAccessible(true); View logoView = (View) declaredField.get(toolbar); logoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } catch (Exception ex) {
Another possible solution would be to set a custom layout in an ActionBar. However, I advocate following the UI / UX guidelines and double checking if the navigation box is important in secondary activities.
source share