1

我正在尝试将 switchcompat 添加到工具栏,菜单项引用自定义布局

工具栏开关.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_marginRight="8dp"
android:layout_height="match_parent">

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    app:showText="false"
    android:id="@+id/switch_online"
    android:layout_centerInParent="true"
    android:layout_height="wrap_content" />

</RelativeLayout>

menu_main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/menu_toggle"
    android:actionLayout="@layout/toolbar_switch"
    app:showAsAction="always"
    android:title="" />
</menu>

如果我将菜单项设置为图像或文本,则菜单在活动中膨胀很好,但是当我将其指向自定义布局时,它不会显示

    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setOnMenuItemClickListener(this);

    switchOnline = (SwitchCompat)toolbar.findViewById(R.id.switch_online);

我的应用主题基于 AppCompat

4

1 回答 1

1

由于您使用的是支持操作栏,因此您需要使用app:actionLayout来指定您的自定义视图。

于 2015-03-12T23:22:47.883 回答