Center the title android

How to center align the ActionBar title in Android?

I am trying to use the following code to center the text in the ActionBar , but it aligns itself to the left.

How do you make it appear in the center?

18 Answers 18

To have a centered title in ABS (if you want to have this in the default ActionBar , just remove the «support» in the method names), you could just do this:

In your Activity, in your onCreate() method:

Now you should have an Actionbar with just a title. If you want to set a custom background, set it in the Layout above (but then don’t forget to set android:layout_height=»match_parent» ).

I haven’t had much success with the other answers. below is exactly what worked for me on Android 4.4.3 using the ActionBar in the support library v7. I have it set up to show the navigation drawer icon («burger menu button»)

XML

Java

Define your own custom view with title text, then pass LayoutParams to setCustomView(), as Sergii says.

EDITED: At least for width, you should use WRAP_CONTENT or your navigation drawer, app icon, etc. WON’T BE SHOWN (custom view shown on top of other views on action bar). This will occur especially when no action button is shown.

EDITED: Equivalent in xml layout:

This doesn’t require LayoutParams to be specified.

Just a quick addition to Ahmad’s answer. You can’t use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view:

Code here working for me.

Without customview its able to center actionbar title. It’s perfectly working for navigation drawer as well

OK. After a lot of research, combined with the accepted answer above, I have come up with a solution that also works if you have other stuff in your action bar (back/home button, menu button). So basically I have put the override methods in a basic activity (which all other activities extend), and placed the code there. This code sets the title of each activity as it is provided in AndroidManifest.xml, and also does som other custom stuff (like setting a custom tint on action bar buttons, and custom font on the title). You only need to leave out the gravity in action_bar.xml, and use padding instead. actionBar != null check is used, since not all my activities have one.

Tested on 4.4.2 and 5.0.1

And my action_bar.xml is like this (if anyone is interested):

EDIT: If you need to change the title to something else AFTER the activity is loaded (onCreateOptionsMenu has already been called), put another TextView in your action_bar.xml and use the following code to «pad» this new TextView, set text and show it:

EDIT (25.08.2016): This does not work with appcompat 24.2.0 revision (August 2016), if your activity has a «back button». I filed a bug report (Issue 220899), but I do not know if it is of any use (doubt it will be fixed any time soon). Meanwhile the solution is to check if the child’s class is equal to AppCompatImageButton.class and do the same, only increase the width by 30% (e.g. appCompatImageButton.getWidth()*1.3 before subtracting this value from the original padding):

In the mean time I threw in some padding/margin checks in there:

Источник

How to center the title of a CollapsingToolbarLayout?

I tried setExpandTitleTextAppearance , but it didn’t work. I want to center the expanded title text.

Читайте также:  Устройство ввода android что это

7 Answers 7

There is an attribute expandedTitleGravity that you can use with the CollapsingToolbarLayout to center the expanded title text. Add this to your CollapsingToolbarLayout:

In my use case, I set app:titleEnabled to false, I didn’t need it anyway. After that, my gravity was respected properly inside the Toolbar layout.

you can arrange the position of the tittle in both the collapsed and expanded state in the following ways

in expanded state,

in collapsed state,

i think this may help you

@Javed, correct me if I wrong, you want to have the title centered in the Toolbar, then CollapsingToolbarLayout is collapsed and your layout is something like this, right?

Then you can do this trick ( i do it in onCreate of the Activity):

The key is that TextView within Toolbar has width property «Wrap Content», so we need to change it to «Match Parent». (See more about this reflection here)

Tested on Android 5.1.1 and Android 4.3 (should work pretty much everywhere)

Источник

The Joy of Custom Views: How to make a centered title Toolbar in Android

Jun 30, 2016 · 5 min read

Custom views in Android can be quite a pain in the ass. I work at a startup in Denmark that specialises in developing mobile apps for clients, and every one of them needs something custom for it to stand out in a crowd.

Custom views are the best and worst part of Android devel o pment for me. The joy of creating a one of a kind is often offset with the terror and headache of either hacking pieces of the framework together and hoping they don’t crash, or drawing everything yourself then finding one tiny hiccup that means the whole thing needs to be restructured.

In any case, in time you build up a long list of do’s and don’ts and little shortcuts here and gotcha’s there, and I thought I’d share them with you good folks, because trying every combination yourself sucks big time.

This article was originally posted on BENDLH.com

A Toolbar with a centered title, easy right?

Centering a title in a toolbar sounds like a stupidly simple thing to do, but from my experience it’s one of those “stupidly simple, provided you already have the answer” kind of things. When I make custom Views, I want them with as few side effects as possible, the best case having it as easy to use as the framework equivalent or easier. So, some constraints:

  • A direct Toolbar replacement which can be used solely in XML, with customizations possible but not necessary.
  • Transparent to any user of the standard Toolbar/Actionbar API.
  • Transparent to the framework (Allows menu items to be inflated as standard, without affecting the centeredness of the title).

So let’s get on with it.

Disclaimer: this view has been created over time with refinements added progressively reflecting my needs. I wish I could promise it will work in every situation, but I can’t. In any case, it’s a damn good place to start if you need something like this with more custom features.

On to the code

Obviously we want to extend the framework Toolbar, as we want as much out of the box as possible:

Every time I build a custom View I end up needing to initialize something when it’s first instantiated. As all Views have at least 3 constructors I create an init() method called in every one of the constructors:

The init() method itself has been boiled down to very little with all the refinements over time:

We get the width of the device’s screen ( see below), then create a TextView, and add it to the Toolbar just like any other layout.

Gotcha 1: When creating this Toolbar I couldn’t for the life of me get the TextView centered in all circumstances. Adding or removing the back button would offset it from the left, and the same would happen on the right with option menu items. Dealing with anything other than the absolute screen size and position just wouldn’t work.

Читайте также:  Шрифты для андроид студио

The exact code to get the device’s screen width can be found pretty easy on StackOverflow, but here it is for ease:

As for the style that’s referenced, we always use AppCompat, but you can just replace the parent with the framework equivalent. Here’s where we set the title color:

This is where things get interesting, at the moment we have a TextView inside out Toolbar, but leaving it at that would give us two titles if we used the Actionbar API’s, and neither one would be centered.

We have our screen width, so now we want to center the title in the Toolbar. The width and height values of any view will be 0 until the first layout pass occurs, so that’s where we’ll center the title.

_centerTitle is a boolean flag we set to enable or disable the centered title. If false we never offset the title, and so it stays on the left, just as the standard framework version.

We use getLocationOnScreen() here to get the absolute X value of the TextView. By subtracting that offset, we can get the exact distance from the title’s current X position and the offset we need to center it, whether we have an Up/Home button or not.

Gotcha 2: Between getX(), getLeft(), getLocationOnScreen(), getLocationInWindow(), and getGlobalVisibleRect(), there’s a lot of View “X” values available. I won’t go into the details of each here, but suffice to say getLocationOnScreen() returns the X and Y values compared to the top left corner of the screen, which is what we want here.

Gotcha 3: You’ve probably also noticed we add the value of _titleTextView. getTranslationX() to the offset value we calculate. This is because as we’re working with a mix of relative offsets ( location and getTranslationX()) and absolute offsets ( _screenWidth) we have to account for any current relative offset. In other words; if the title is already centered, but is being laid out again (When we change title text for example) — location [0] will equal _screenWidth / 2 — _titleTextView. getWidth() / 2, so without the g etTranslationX() call, the offset will be set to 0, moving the text back to the left.

These two methods simply override the default Toolbar implementation and update our title instead of the stock one. We call requestLayout() to ensure that the text is re-centered in case the new title is longer or shorter than the original.

Gotcha 3: One of the many issues I had making this was trying to understand why the Actionbar API’s weren’t working with my custom Toolbar. It finally boiled down to a stupidly small difference; my setTitle() method took a String as a parameter, rather than a CharSequence, so didn’t override the default Toolbar implementation. Also don’t forget to include the int resource version as well, as you may never use it in your code, but the framework might.

Last but not least:

I personally hard code the value to true when the field is declared, but that’s up to you.

And that’s pretty much it. Stupidly simple eh? I hope this proves useful to any budding Android devs out there, and saves you the hassle I went through getting this working right. Feel free to recommend or share this, it can only help out everyone involved. Until next time, happy coding!

Источник

Android: How to Center title in ToolBar

I am using ToolBar in my project first time, so i do not know how to customized the toolbar in android. I need to centered title in to the tool bar and how to do that please tell me.

Читайте также:  Бесконтактная оплата андроид виза

Thank in advance.

19 Answers 19

The problem with simply adding a TextView in the Toolbar aligned center is adding menu items in the toolbar which will offset the centered text.

To get around this, I’ve layered the text on top of the Toolbar, not inside it. This way it doesn’t matter how many icons you add, it will not offset the centered text:

This way there is no need for any extra logic to compensate for the offset spacing of back buttons/overflow menu/search icons etc. on the toolbar, because the centered text is above it, not in it.

Remember that Toolbar is just a ViewGroup like the others. So you can stuff View s into it. In your case, you need a TextView inside a Toolbar .

Now, set the Toolbar as your action bar by first retrieving it and then using the setSupportActionBar() .

Since the gravity of the TextView is set to center , the text must be centered.

You can force the toolbar to the center by wrapping title and level right padding which has default left padding for title. Then put background color to the parent of toolbar and that way part which is cut out by wrapping title is in the same color(white in my example):

ToolBar is a View Group. so To Center Align The text Use

Just putting another TextView inside Toolbar is not enough to get title centered relative to the screen, its position will be dependent on other items in a toolbar (back button, menu items).

To make title centred you can manually set its position:

Extend android.support.v7.widget.Toolbar class and make following changes:

  1. add TextView
  2. override onLayout() and set TextView location to centre it ( titleView.setX((getWidth() — titleView.getWidth())/2) )
  3. override setTitle() where set title text to new text view

In layout you can use this class like this:

Источник

Custom dialog on Android: How can I center its title?

I’m developing an Android application.

How can I center the title for a custom dialog that I’m using?

13 Answers 13

Another way that this can be done programatically is using the setCustomTitle():

Just found this post while trying to figure out how to do the same thing. Here’s how I did it for anyone else that finds this in the future.

Style xml is as follows:

And in my activities onCreateDialog method for the dialog I want styled I create the dialog like this:

You can do it in code as well. Assume you have dialog fragment then add following lines of code.

For your custom DialogFragment you can do this:

You can do it programmatically without custom view:

Thanks @hesam for the idea. For appcompat layout see Android/sdk/platforms/android-26/data/res/layout/alert_dialog_title_material.xml

Similar to @LandL Partners solution, but in Kotlin:

If you don’t call AlertDialog.Builder.setIcon() and AlertDialog.Builder.setTitle() , then your custom dialog will not show the built-in/default title View. In this case you are able to add your custom title View:

As soon as it is you who create this View it is possible to implement any type of alignment.

You’ve got some starting tips here for modifying the title of a dialog: Android — change custom title view at run time Don’t know if it can be centered(haven’t tried), but if it’s a custom View I guess it’s very possible.

Here’s a nasty solution. Extend AlertDialog.Builder and override all the methods (eg. setText, setTitle, setView, etc) to not set the actual Dialog’s text/title/view, but to create a new view within the Dialog’s View do everything in there. Then you are free to style everything as you please.

To clarify, as far as the parent class is concerned, the View is set, and nothing else.

As far as your custom extended class is concerned, everything is done within that view.

Источник

Оцените статью