java - 如何将 ActionBar 标题设置在中间而不是默认的左对齐位置?

标签 java android xml android-actionbar

尝试将 ActionBar 标题设置在中间而不是默认的左对齐位置。为此,根据其他答案,这就是我所做的:

    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbarDownloads);
    setSupportActionBar(myToolbar);
    if(getSupportActionBar()!=null)
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.actionbar_layout);
    }

actionbar_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Downloads"
        android:layout_centerInParent="true"
        android:textColor="#000000"
        android:id="@+id/mytext"
        android:textSize="18sp" />

</RelativeLayout>

但是,这不会产生预期的结果(即呈现文本但仍然左对齐),这种方法有什么问题以及如何解决这个问题?

最佳答案

尝试使用自定义 Toolbar

<android.support.v7.widget.Toolbar
    android:id="@+id/ar_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="exitUntilCollapsed"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Center"
        android:orientation="vertical">

        <TextView
             android:id="@+id/toolbar_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center" />
    </LinearLayout>

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

现在在 java 文件中

private Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.ar_toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
 mTitle.setText("Nilesh Rathod");
setSupportActionBar(toolbar);

关于java - 如何将 ActionBar 标题设置在中间而不是默认的左对齐位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46558006/

相关文章:

xml - 使用 Jenkins 显示自定义 HTML 或 XML 报告

android - 比屏幕大的ImageView作为背景

android - 如何在Android Studio中添加libandenginephysicsbox2dextension.so文件|和引擎

c# - 使用 where 子句从父节点中删除子 XML 节点

java - 导入 java.awt.* 错误

java - Xamarin Java.Lang.Object 创建效率低下

php - 文档类型错误

java - 如何根据键集获取两个映射的差异?

java - 玩框架 FORM 绑定(bind)到 Set 而不是 List

java - 接口(interface)和抽象类中的相同方法