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

醉酒当歌 提交于 2019-12-25 04:47:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28637822/android-how-to-center-a-component-in-a-custom-view-in-action-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!