如何获取工具栏的自定义视图

How to get custom view for Toolbar

我已经为 fargments 的工具栏创建了一个自定义视图,我在视图中添加了两个 ImageButtons,并从菜单资源中删除了这些项目。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/actionBarSize"
    android:id="@+id/tool_bar"
    android:background="@color/white">

    <ImageButton
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/video_camera"
        android:icon="@drawable/camcorder_pro_96px"
        android:layout_gravity="left|center_horizontal" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/photo_camera"
        android:icon="@drawable/compact_camera_96px"
        android:layout_gravity="right|center_horizontal"
        />

</android.support.v7.widget.Toolbar>

我已将此视图附加到我的 MainActivity 中的工具栏

toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);

问题是您在 Imagebutton 中将图像设置在错误的属性上,我认为 android:icon 也不存在。

您需要将图像设置为android:src属性才能将图像设置为视图

android:icon

It is displayed to users when a representation of the activity is required on-screen.

因为你应该使用 android:src 而不是 android:icon .

android:src

Sets a drawable as the content of this ImageView or ImageButton.