Подтвердить что ты не робот

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

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

Спасибо заранее.

4b9b3361

Ответ 1

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

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Some Fancy Title"
        android:gravity = "center"
        android:id="@+id/toolbar_title" />

</android.support.v7.widget.Toolbar>

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

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

Ответ 2

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

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

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
        </android.support.v7.widget.Toolbar>

        <TextView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"/>

    </RelativeLayout>
</android.support.design.widget.AppBarLayout>

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

Ответ 3

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

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

            <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:layout_width="wrap_content"
               android:layout_height="56dp"
               android:layout_gravity="center_horizontal"
               android:paddingEnd="15dp"
               android:paddingRight="15dp"
               android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
               app:titleTextColor="@color/black"/>

</android.support.design.widget.AppBarLayout>

Ответ 4

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

app_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/in.chabu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:theme="@style/ToolBarTheme" 
    android:minHeight="?attr/actionBarSize">

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_sign_up"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" 
        android:textStyle="bold"
        android:textColor="@android:color/white"/>

</android.support.v7.widget.Toolbar>

activity_sign_up

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.chabu.activities.SignUpActivity" >

    <include 
        android:id="@+id/tool_bar"
        layout="@layout/app_bar"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tool_bar"
        android:text="@string/hello_world" />

</RelativeLayout>

Avtivity

public class SignUpActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);

        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }


}

Ответ 5

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

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

Ответ 6

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

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

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

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

        private TextView titleView;

        public CenteredToolbar(Context context) {
            this(context, null);
        }

        public CenteredToolbar(Context context, @Nullable AttributeSet attrs) {
            this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
        }

        public CenteredToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);

            titleView = new TextView(getContext());

            int textAppearanceStyleResId;
            TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                    new int[] { android.support.v7.appcompat.R.attr.titleTextAppearance }, defStyleAttr, 0);
            try {
                textAppearanceStyleResId = a.getResourceId(0, 0);
            } finally {
                a.recycle();
            }
            if (textAppearanceStyleResId > 0) {
                titleView.setTextAppearance(context, textAppearanceStyleResId);
            }

            addView(titleView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            titleView.setX((getWidth() - titleView.getWidth())/2);
        }

        @Override
        public void setTitle(CharSequence title) {
            titleView.setText(title);
        }
    }

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

<com.example.CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ToolbarTheme"/>

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

Ответ 7

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

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/lib_action_bar_filter_view_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:gravity="center">

    <TextView
        android:id="@id/lib_action_bar_filter_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:maxLines="2"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:textColor="@android:color/white"
        android:textSize="15sp"/>

</RelativeLayout>

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

/**
 * Customized the <code>RelativeLayout</code> inside the <code>Toolbar</code>.
 * Because by default the custom view in the <code>Toolbar</code> cannot set
 * width as our expect value. So this class allows setting the width of the
 * <code>RelativeLayout</code> to take up any percentage of the screen width.
 */
public class CenteredToolbar extends Toolbar {

private static final double WIDTH_PERCENTAGE = 0.8;

private TextView titleView;

public CenteredToolbar(Context context) {
    this(context, null);
}

public CenteredToolbar(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
}

public CenteredToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View view = this.getChildAt(i);
        if (view instanceof RelativeLayout) {
            int width = getMeasuredWidth();
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.width = (int) (width * WIDTH_PERCENTAGE);
            view.setLayoutParams(layoutParams);
            break;
        }
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View view = this.getChildAt(i);
        if (view instanceof RelativeLayout) {
            forceTitleCenter(view);
            break;
        }
    }
}

/**
 * Centering the layout.
 *
 * @param view The view to be centered
 */
private void forceTitleCenter(View view) {
    int toolbarWidth = getMeasuredWidth();
    int relativeLayoutWidth = view.getMeasuredWidth();
    int newLeft = (int) (toolbarWidth - relativeLayoutWidth) / 2;
    int top = view.getTop();
    int newRight = newLeft + relativeLayoutWidth;
    int bottom = view.getBottom();
    view.layout(newLeft, top, newRight, bottom);
}
}

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

<?xml version="1.0" encoding="utf-8"?>
<com.chinalwb.CenteredToolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/vmosolib_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    app:contentInsetEnd="0dp"
/>

Ответ 8

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

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/profile_image"
            android:layout_width="44dp"
            android:layout_height="55dp"
            android:src="@drawable/profile"
            app:civ_border_color="@color/secondary_text"
            app:civ_border_width="2dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Title"
            android:gravity="center"
            style="@style/Base.TextAppearance.AppCompat.Widget.ActionBar.Title"
            />


    </android.support.v7.widget.Toolbar>

Ответ 9

public void centerTitleAndSubtitle(Toolbar toolbar){
    // Save current title and subtitle
    final CharSequence originalTitle = toolbar.getTitle();
    final CharSequence originalSubtitle = toolbar.getSubtitle();

    // Temporarily modify title and subtitle to help detecting each
    toolbar.setTitle("title");
    toolbar.setSubtitle("subtitle");

    for(int i = 0; i < toolbar.getChildCount(); i++){
        View view = toolbar.getChildAt(i);

        if(view instanceof TextView){
            TextView textView = (TextView) view;


            if(textView.getText().equals("title")){
                // Customize title TextView
                Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                textView.setLayoutParams(params);

            } else if(textView.getText().equals("subtitle")){
                // Customize subtitle TextView
                Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                textView.setLayoutParams(params);
            }
        }

        // Restore title and subtitle
        toolbar.setTitle(originalTitle);
        toolbar.setSubtitle(originalSubtitle);
    }
}

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

Ответ 10

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

     <android.support.v7.widget.Toolbar           
         android:layout_width="match_parent"
         android:layout_height="?attr/actionBarSize"
         android:animateLayoutChanges="true"
         android:backgroundTint="@color/colorPrimary"
         android:background="?attr/colorPrimary"
         android:elevation="4dp"
         android:minHeight="?android:attr/actionBarSize"
         app:layout_collapseMode="pin"
         app:layout_scrollFlags="scroll|exitUntilCollapsed"
         app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
         app:popupTheme="@style/AppTheme.PopupOverlay"
         app:titleTextAppearance="@style/Toolbar.TitleText" >

      <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/toolbar_title"
            android:text="Title"
            android:layout_gravity="center"/>

     </android.support.v7.widget.Toolbar>

Ответ 11

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

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:collapsedTitleGravity="center"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="20dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">


            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="pin"
                app:titleMarginTop="10dp"
                app:layout_scrollFlags="scroll|enterAlways" ></android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

Ответ 12

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

Ответ 13

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

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

import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import android.view.Gravity

class CenteredToolbar(context: Context, attrs: AttributeSet?, defStyleAttr: Int):
Toolbar(context, attrs, defStyleAttr) {

constructor(context: Context) : this(context, null, 0)

constructor(context: Context, attrs: AttributeSet) : this(context, attrs, androidx.appcompat.R.attr.toolbarStyle)

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    super.onLayout(changed, l, t, r, b)

    val childCount = childCount
    for (i in 0 until childCount) {
        val view = this.getChildAt(i)
        if (view is TextView) {
            forceTitleCenter(view,l, r)
            break
        }
    }
}

/**
 * Centering the layout.
 *
 * @param view The view to be centered
 */
private fun forceTitleCenter(view: TextView, l: Int,  r: Int) {
    val top = view.getTop()
    val bottom = view.getBottom()
    view.layout(l, top, r, bottom)
    navigationIcon?.let{
        view.setPadding(it.intrinsicWidth,0,0,0)
    }
    view.gravity = Gravity.CENTER
}

}

 <ui.customView.CenteredToolbar
                android:id="@+id/apd_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:navigationIcon="@drawable/ic_search"
                app:title="Check Title"
                app:elevation="4dp"/>

Ответ 14

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

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

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>

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

Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);

Ответ 15

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

public class CenterTitleToolbar extends Toolbar {
    private AppCompatTextView titleTextView;


    public CenterTitleToolbar(Context context) {
        super(context);
    }

    public CenterTitleToolbar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CenterTitleToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setTitle(CharSequence title) {
        if (!TextUtils.isEmpty(title)) {
            if (titleTextView == null) {
                final Context context = getContext();
                titleTextView = new AppCompatTextView(context);
                titleTextView.setSingleLine();
                titleTextView.setEllipsize(TextUtils.TruncateAt.END);
                titleTextView.setTextAppearance(context, R.style.TextAppearance_MaterialComponents_Headline6);
                final LayoutParams lp = generateDefaultLayoutParams();
                lp.gravity = Gravity.CENTER;
                titleTextView.setLayoutParams(lp);
            }
            if (titleTextView.getParent() != this) {
                addSystemView(titleTextView);
            }
        } else if (titleTextView != null && titleTextView.getParent() == this) {
            removeView(titleTextView);
        }
        if (titleTextView != null) {
            titleTextView.setText(title);
        }
    }

    private void addSystemView(View v) {
        final ViewGroup.LayoutParams vlp = v.getLayoutParams();
        final LayoutParams lp;
        if (vlp == null) {
            lp = generateDefaultLayoutParams();
        } else if (!checkLayoutParams(vlp)) {
            lp = generateLayoutParams(vlp);
        } else {
            lp = (LayoutParams) vlp;
        }
        addView(v, lp);
    }

}

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

Ответ 16

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

Toolbar toolbar = findViewById(R.id.mytoolbar);
        TextView titleText = getProperties(new TextView(this));
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
        frameLayout.addView(titleText);
        toolbar.addView(frameLayout);
        setSupportActionBar(toolbar);

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

 private TextView getProperties(TextView titleText){
        titleText.setText(wallpaperName);
        titleText.setTextColor(Color.WHITE);
        titleText.setTextSize(18f);
        titleText.setShadowLayer(2f,2f,2f,Color.BLACK);
        titleText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); // CENTER ALIGNMENT
        return titleText;
    }

Ответ 17

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

app:contentInsetStart="150dp"

Ответ 18

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

SupportActionBar.Title = "title";

Ответ 19

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

name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"

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

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

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    app:title="Title"
    app:titleMarginStart="155dp"
    app:titleTextColor="@android:color/white" />

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