I want to create my own ActionBar
Layout.
Like this (created in Paint for example)
Is it possible to give the second Button the Up-Navigation Properties? So if I press it, it finish this Activity
and starts it's parent.
I want to have the burger Icon for the Navigation Drawer
, the Up-Icon for Up-Navigation and the Title of the Activity.
Is it possible? Or is there a solution already?
Actually, it's fairly easy(though it's little hacky) to do. First, create a drawable for back button(preferably - as a selector, to distinguish 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>
Next, set this drawable to the logo of the toolbar toolbar.setLogo(R.drawable.back_button_selector);
Then the only thing left is to set 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's 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 Nicola's post here). Or if you are not scared of reflection, it can be easily done like this:
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) {
//error
}
Another possible solution would be to set custom layout to the ActionBar. Though, I'm advocating to follow the UI/UX guidelines and double-check, if navigation drawer is essential in the secondary activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With