简体   繁体   English

Android中标题栏文本居中对齐

[英]Center align of text of title bar in Android

I'm new at Android programming so I don't know all the features.我是 Android 编程新手,所以我不知道所有功能。 As I understood, all generated activities has a title bar which contains app_name string resource.据我了解,所有生成的活动都有一个标题栏,其中包含 app_name 字符串资源。 I managed to change title of sole activity but I don't understand how to change alignment of the text of the title.我设法更改了唯一活动的标题,但我不明白如何更改标题文本的对齐方式。 I mean, the're generated like this:我的意思是,它们是这样生成的:

在此处输入图片说明

but I need it to be like this:但我需要它是这样的:

在此处输入图片说明

If you are using support toolbar , the approach will be easy.如果您使用的是支持工具栏,则该方法将很容易。 just add a text view inside it and make it centered :只需在其中添加一个文本视图并使其居中:

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

in your activity you can access the title like so:在您的活动中,您可以像这样访问标题:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_top);
TextView Title = (TextView) toolbar.findViewById(R.id.toolbar_title);

To have a centered title in ABS (if you want to have this in the default ActionBar, just remove the "support" in the method names), you could just do this:要在 ABS 中有一个居中的标题(如果你想在默认的 ActionBar 中有这个,只需删除方法名称中的“支持”),你可以这样做:

In your Activity, in your onCreate() method:在您的活动中,在您的onCreate()方法中:

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
getSupportActionBar().setCustomView(R.layout.abs_layout);

xml file xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_gravity="center"
        android:text="my Title"
        android:textColor="#ffffff"
        android:id="@+id/mytext"
        android:textSize="18sp" />

</LinearLayout>

Now you should have an Actionbar with just a title.现在你应该有一个只有标题的 Actionbar。 If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent").如果要设置自定义背景,请在上面的 Layout 中进行设置(但不要忘记设置 android:layout_height="match_parent")。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM