在ActionBar中居中自定义视图的Android实现

7

我想设置一个自定义视图来替换我的操作栏,但是问题是它没有填满整个操作栏的宽度,这使得我很难居中对象。如何设置一个填满整个操作栏的自定义视图呢?

设置操作栏的代码:

actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionBar.setCustomView(inflater.inflate(R.layout.actionbar_layout, null));

我的 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:layout_gravity="center"
    android:background="#EDEDED">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="#FFFFFF"
    android:text="Testing"/>
</RelativeLayout>

https://dev59.com/SGQo5IYBdhLWcg3wdPS8#16029214 - Dhaval Parmar
2个回答

2

就我个人而言,问题在于上层布局总是被拉伸到内部视图的高度和宽度。您可以通过在TextView中设置layout_height="match_parent"来使其正常工作:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/actionbar_title"
        />
</LinearLayout>

2

在actionbar_layout.xml中,您需要为RelativeLayout设置android:layout_width="wrap_content";这个属性和android:layout_gravity="center"一起使用,可以让您的自定义视图在ActionBar中居中显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接