I want to display the logo at the centre of the Action Bar. Here's my custom layout code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ActionBarWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/logo"
android:layout_centerInParent="true"
android:padding="8dp"/>
</RelativeLayout>
And in the onCreate()
I'm using it as:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_logo);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2A2A2A")));
The issue is it displays fine in normal Fragments and Activity but shifts a little to the right when used with Navigation Drawer. Here are the images:
- Wrong One:
- Right One:
What am I doing wrong? Thanks.
I used a Drawable as background of the Action Bar. In this way you can use different MenuItem on left and/or right and the logo will be everytime centered. I needed to animate also the logo when it has been loaded through Picasso, and this is the result:
I've used a LayerDrawable for animating just one Drawable (a layer) into it. This is the code, maybe could be useful for someone:
And this is the showActionBarLogo function for showing and hiding the Action bar logo:
I've created a drawable for the Action Bar with:
I load the logo with Picasso and I like to animate it when has been loaded (bitmap onBitmapLoaded callback).
Bear in mind to declare Picasso Target out of showActionBarLogo function to avoid garbage issue on loading images:
If you don't need the Picasso loading, you can use only the code into
onBitmapLoaded
function and using a Drawable instead of the bitmap variable.Same thing if you don't need the fade animation. You can remove the
layers[1].setAlpha(0);
line and also all theObjectAnimator
lines.I've tested it from Android 4.4 (api 19) to 8.1 (api 27) and it works great!
I hope this could help!
Using the attribute clip_horizontal did the trick for me.
Then try ToolBar. Try this code
Try using Linear layout and
layout_gravity
like this :hope it help
Add
app:contentInsetLeft="0dp"
to yourandroid.support.v7.widget.Toolbar
, because a toolbar with menu drawer will automatically have a right margin.