在AppBarLayout中用MaterialToolbar将标题居中。

问题描述 投票:-1回答:1

我试着将文字放在工具栏的中心。我使用 AppBarLayoutMaterialToolbar如上所述 材料设计.

我尝试了我在StackOverflow上找到的所有方法来使标题居中,但似乎没有任何效果。

这是我的工具条。

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/topAppBar"
        style="@style/CenteredToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize" />

</com.google.android.material.appbar.AppBarLayout>

And CenteredToolbar 是我的自定义样式,我试图将标题居中。

<style name="CenteredToolbar" parent="Widget.MaterialComponents.Toolbar.Primary">
    <item name="android:gravity">center_horizontal</item>
</style>

然而,这并不工作。

有什么建议可以让标题居中?

android material-design android-toolbar android-appbarlayout
1个回答
0
投票

不幸的是,我只找到了这个方法来创建一个居中的标题在工具栏。

奖金。 你将有一个完整的控制工具栏的用户界面。

创建一个自定义的布局,像这样使用它作为工具条。

活动_action_bar

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_preference"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal">

<TextView
    android:id="@+id/actionbar_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:maxLines="1"
    android:clickable="false"
    android:focusable="false"
    android:longClickable="false"
    android:fontFamily="@font/lato"
    android:textStyle="bold"
    android:textSize="20sp"
    android:textColor="@color/colorTextMain" />

</LinearLayout>

在你的 界面 布局XML包括这样的工具栏。

<include layout="@layout/activity_action_bar" />

现在在你用前面的界面布局setContentView的类中这样做。

    setContentView(R.layout.activity_interface);
    // create and define a custom action bar
    View view = getLayoutInflater().inflate(R.layout.activity_action_bar, null);
    ActionBar.LayoutParams params = new ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.MATCH_PARENT,
            Gravity.CENTER);
    TextView Title = view.findViewById(R.id.actionbar_title);
    Title.setText(getString(R.string.about));
    getSupportActionBar().setCustomView(view,params);
    getSupportActionBar().setDisplayShowCustomEnabled(true); // show custom title
    getSupportActionBar().setDisplayShowTitleEnabled(false); // hide the default title
    getSupportActionBar().setElevation(0);
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
    getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.colorPrimary))); // set background

这将给你一个完整的工具条管理,如居中的标题或自定义UI。

结果是这样的。result

© www.soinside.com 2019 - 2024. All rights reserved.