如何在中间设置ActionBar标题而不是默认的左对齐位置? [英] How to set the ActionBar title in middle instead of the default left aligned position?

查看:261
本文介绍了如何在中间设置ActionBar标题而不是默认的左对齐位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to set the ActionBar title in middle instead of the default left aligned position. To do so, based on other answers this is what I've done:

    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>

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

However, this does not produce the intended result (ie this renders the text however still is left aligned), what's wrong with this approach and how to fix this?

推荐答案

尝试使用自定义工具栏

<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);

这篇关于如何在中间设置ActionBar标题而不是默认的左对齐位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆