自定义 ActionBar 标题未居中对齐

Custom ActionBar title is not being center aligned

我正在创建自定义 actionBar。一切正常,但我未能将文本放在 actionBar 的中心。在互联网上搜索了很多解决方案,但 none 对我来说。任何人都可以帮助我实现它。我试图实现以下问题的答案,但它也没有效果。How to center align the ActionBar title in Android?

虽然我可以通过为 textview 提供填充来将文本置于中心,但我认为这不是正确的方法。

代码如下:

自定义 ActionBar 代码:

private void createCustomActionBarTitle()
{
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8B58A3")));

    LayoutInflater inflater = LayoutInflater.from(this);
    View v = inflater.inflate(R.layout.titleview, null);

    TextView frag1 = (TextView)v.findViewById(R.id.titleFragment1);
    frag1.setTypeface(vivaldiiFont);

    actionBar.setCustomView(v);
}

和xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/actionBar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingTop="7dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/titleFragment1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Title"
        android:textSize="20sp"
        android:textColor="#FFFFFF"
        android:layout_gravity="center" />

这就是 actionBar 现在的样子

此文本应居中而不是偏左。

<?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="match_parent"
android:orientation="horizontal"
android:background="@drawable/header" > 

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:id="@+id/mytext"
    android:textColor="@color/header_text_color"
    android:textSize="18sp"
    android:textStyle="bold"/>
 </RelativeLayout> 

这样做你会得到你想要的。

试试这个...

1. custom_action_bar.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:layout_gravity="center"
android:background="@android:color/holo_blue_light" >

<TextView
    android:id="@+id/apptitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center_horizontal|center_vertical"
    android:gravity="center_horizontal|center_vertical"
    android:padding="8dp"
    android:text="@string/app_name"
    android:textColor="#FFFFFF"
    android:textSize="16sp" />

 </RelativeLayout>