设置操作栏的样式

Styling the Action Bar

我正在尝试通过在左侧添加一个自定义后退按钮并在中间添加一个图标来设置操作栏的样式。 Android Studio 中的渲染完全符合我的要求,但是当我在 phone 上测试布局时,它只在左侧显示后退按钮和图标,图标在背面顶部按钮。这是我的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      
    android:id="@+id/action_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageButton android:id="@+id/back_button"
        android:contentDescription="Image"
        android:src="@drawable/back_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="@color/action_bar_bg_color"
        android:layout_alignParentLeft="true"/>

    <ImageView android:id="@+id/cow_icon"
        android:contentDescription="Image"
        android:src="@drawable/cowhead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"/>

</RelativeLayout>

这就是我为操作栏设置样式所做的:

ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    View mActionBar = getLayoutInflater().inflate(R.layout.action_bar_layout, null);
    actionBar.setCustomView(mActionBar);
    actionBar.setDisplayShowCustomEnabled(true);

有人看到可能导致操作栏样式有缺陷的原因吗?

您可以尝试使用新的工具栏:https://developer.android.com/reference/android/widget/Toolbar.html 这非常适合制作自定义 actionBar。

否则,您不必自定义后退按钮,操作栏支持它:https://developer.android.com/reference/android/app/ActionBar.html#setDisplayHomeAsUpEnabled(boolean)