Android toolbar center title

Centering toolbar title

I have a custom toolbar and I’m utilizing TextSwitcher . My issue is I’m centering the text but when I apply the back button the text moves to the right. I’m assuming this is caused by the button creating it’s own layout moving the existing one over. I noticed the text is centered again if I enable the options on the toolbar but I do not want this. I tried setting the visibility of the options to hidden but that seems to remove the element completely. I’d rather not create a custom back button so any help would be appreciated. The following code is in my onCreate method in my Activity :

2 Answers 2

best bet is to create a Toolbar and include a Layout in the Toolbar which allows positioning:

or in your specific case use the TextSwitcher

I am assuming you are trying to animate the toolbar title, so here is what i did to manage that:

-First you need a FrameLayout parent for the title so when you animate it you wont overlap with some icons (most notably the drawer icon)

-Then comes the simple TextView, which is the title, just use ToolBarTitle style and you wont need anything else.

When you inflate the toolbar layout, be sure the set the original toolbar title to a empty string so it wont overlap our custom

Now you can easily animate the title as you wish, here is my implementation, which animates the title sliding in from the left and sliding out to the left, every time i change the title.

Источник

How to center the title of a CollapsingToolbarLayout?

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

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)

Источник

Toolbar title not in center when Back Button is enable

I’m trying to display my toolbar title in the center and to do it I use the method which is given in this answer :-Toolbar Center title

However, when I enable back button in my activity by following code:

The title of toolbar doesn’t show up in the center but slightly off-centered towards the right.

How can I achieve centered title without being affected by the back button or menu bar?

8 Answers 8

Add a TextView inside the Toolbar & don’t forget to set the following attribute inside your TextView.

OR

Refer to this tutorial for more information.

Having a placeholder image the same size as the back arrow and setting it to be invisible when the back arrow is not shown and gone when it’s displayed did the trick for me.

Just add android:paddingEnd=»72dp; to the Toolbar layout.

The reason why the title is not centered when you use a back button as navigation icon, is that navigation icon is represented as AppCompatImageButton and is added to the same layout as your title TextView . Using Arshak’s answer is not a bad idea, but ?android:attr/actionBarSize is not a good way to define the end margin. As the action bar height is probably the same size as icon’s width, it might work, but might not work on all devices. Could be a good idea to specify this size from material design guidelines.

Just put your content in a child view inside the Toolbar tag in XML, using the following attributes:

Offical docs for Toolbar state:

One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view’s LayoutParams indicates a Gravity value of Gravity#CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.

Источник

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.

Читайте также:  Android apps use java

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:

Источник

Android: как заголовок центра в ToolBar

Я использую ToolBar в моем проекте в первый раз, поэтому я не знаю, как настроить панель инструментов в android. Мне нужно сфокусировать заголовок на панели инструментов и как это сделать, пожалуйста, скажите мне.

ОТВЕТЫ

Ответ 1

Помните, что Toolbar — это просто ViewGroup , как и другие. Таким образом, вы можете вставить в него View . В вашем случае вам понадобится TextView внутри Toolbar .

Теперь установите Toolbar в качестве панели действий, сначала извлекая ее, а затем используя setSupportActionBar() .

Так как значение силы TextView установлено на center , текст должен быть центрирован.

Ответ 2

Проблема с простое добавление TextView в выравниваемом центре панели инструментов добавляет пункты меню на панели инструментов, которые будут смещать центрированный текст.

Чтобы обойти это, я наложил текст поверх панели инструментов, а не внутри него. Таким образом, не важно, сколько значков вы добавляете, это не будет компенсировать центрированный текст:

Таким образом, нет необходимости в дополнительной логике, чтобы компенсировать смещение интервалов между кнопками/переполнениями меню/иконками переполнения и т.д. на панели инструментов, потому что центрированный текст находится над ним, а не в нем.

Ответ 3

Вы можете принудительно установить панель инструментов в центр, обернув заголовок заголовком и уровнем справа, который по умолчанию оставил дополнение для заголовка. Затем поместите цвет фона в родительский элемент панели инструментов, и в этом случае часть, вырезанная заголовком, будет иметь один и тот же цвет (белый в моем примере):

Ответ 4

ToolBar — группа просмотра. так что Выравнивание центра Текст Используйте

Ответ 5

Когда у вас есть кнопка «Домой» или «Вверх» вместе с центральным заголовком, а заголовок больше не центрирован и немного сдвинут вправо, установите текст в виде width = wrap_content и layout_gravity = center

Читайте также:  The android sdk location contains non ascii characters

Ответ 6

Просто поставить еще один TextView внутри Toolbar недостаточно, чтобы получить центрирование по центру относительно экрана, его позиция будет зависеть от других элементов на панели инструментов (кнопка возврата, элементы меню).

Чтобы сделать центрирование по центру, вы можете вручную установить свою позицию:

Разверните android.support.v7.widget.Toolbar класс и внесите следующие изменения:

  • добавить TextView
  • переопределить onLayout() и установить TextView местоположение, чтобы центрировать его ( titleView.setX((getWidth() — titleView.getWidth())/2) )
  • переопределить setTitle() , где установить текст заголовка в новое текстовое представление

В макете вы можете использовать этот класс следующим образом:

Кроме того, чтобы новый текст заголовка выглядел как стандартный заголовок, вы должны применить стиль titleTextAppearance к новому TextView ( titleView.setTextAppearance(context, textAppearanceStyleResId) ).

Ответ 7

Окончательный интерфейс выглядит следующим образом: Для моего проекта у меня есть значок навигации слева и меню (более 1) справа, и я хочу поместить заголовок в центр.

У меня есть setSupportActionBar(toolbar) и _actionBar.setCustomView(R.layout.actionbar_filter); , Мой файл макета:

Моя панель инструментов расширяет android.support.v7.widget.Toolbar, затем (вид жесткого кода) измеряет размер RelativeLayout и, наконец, размещает его в горизонтальном центре.

Прикрепить мой макет панели инструментов. Может быть, вам это не нужно, я просто вставляю сюда для кого-то ссылки:

Ответ 8

Поскольку панель инструментов представляет собой группу представлений, чтобы вы могли создавать макеты внутри нее. Выполните следующие шаги.

1. Создайте текстовое изображение внутри панели инструментов. 2 — сделайте свой центр тяжести текстуры

Ответ 9

Если вы также хотите использовать собственный шрифт, посмотрите мой другой ответ здесь: fooobar.com/questions/28770/.

Ответ 10

Использовать пользовательский заголовок (с центром тяжести) внутри панели инструментов

Ответ 11

установить значение collapsedTitleGravity в центр

Ответ 12

Лучшим решением будет использовать вложенную TextView в ToolBar затем установите layout_width и layout_height к wrap_content . Затем установите layout_gravity в center . Таким образом, он не компенсируется другими значками на toolbar .

Ответ 13

Основано на @LiuWenbin_NO,

Я создал пользовательскую панель инструментов, которая не нуждалась в дополнительном представлении для центрирования заголовка в текстовом представлении,

Ответ 14

Я тебя не понял Вопрос Полностью.. но я нашел Решение Как этот

Чтобы использовать пользовательский заголовок на панели инструментов, все, что вам нужно сделать, это помнить, что панель инструментов — просто причудливая ViewGroup, поэтому вы можете добавить собственный заголовок так:

Это означает, что вы можете стилизовать TextView, но хотите, потому что это просто обычный TextView. Поэтому в вашей деятельности вы можете получить доступ к названию так:

Ответ 15

Я немного изменил источник Toolbar чтобы выровнять центр заголовка.

Стиль текста TextAppearance_MaterialComponents_Headline6 включен в новую библиотеку материалов Android.

Ответ 16

Это сделал мою работу!

Метод для установки свойств TextView

Ответ 17

Простое использование contentInsertStart

Ответ 18

вы можете вставить этот код в свой код

Ответ 19

Я думаю, что это будет работать.

изменить базовую тему в values /styles.xml

Чем добавить панель инструментов вручную, как это

Но это не очень хорошая идея, это не работает хорошо.

Источник

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