简体   繁体   中英

Android: How to center a component in a custom view in action bar?

I have a layout like this :

<?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="50dp" >

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_toRightOf="@+id/backToScan"
        android:gravity="center"
        android:textAllCaps="true"
        android:textAppearance="?android:attr/textAppearanceLarge"

        android:textStyle="bold" />

    <ImageView
        android:id="@+id/backToScan"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="8dp"
        android:src="@drawable/back_button" />

</RelativeLayout>

Now I added it successfuly as a custom view for action bar . But the problem is i cannot center the TextView , I have used a lot of way like android:gravity="center" , android:layout_centerHorizontal="true" , but it doesn't work.

It always float to the left. How can I center it?

在此处输入图片说明

The options menu is preventing the centering of the TextView . Add the following to your Activity :

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    return false;
}

Now it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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