操作栏自定义组件(自定义开关)未与actionLayout一起显示



我想在操作栏中进行自定义切换。这是我的菜单xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autolux="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/actionbar_notification_switch"
    android:title=""
    android:actionLayout="@layout/notification_switch"
   autolux:showAsAction="always"/>
</menu>

这是我的自定义通知开关xml notification_switch.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/color"
    android:textOff="OFF"
    android:textOn="ON"
    android:thumb="@drawable/navigation_switch_selector"
    android:checked="false"
    android:id="@+id/actionbar_notification" />
</RelativeLayout>

这就是我在活动中所说的:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.notification_menu, menu);
        return true;
    }

但是我的操作栏没有显示我的自定义开关(或者任何其他组件,如果我把它放在notification_switch.xml中的话)。此外,我可以将main.xml菜单设置为我的菜单,它只使用一个图标,这很有效。代码是:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:autolux="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_bar_filter"
        android:icon="@drawable/ic_sort"
        android:title="@string/action_settings"
        autolux:showAsAction="always" />
</menu>

我似乎不知道我的自定义组件出了什么问题。任何帮助都将不胜感激。(其他信息是:Min Sdk版本14,Compile Sdk Version 19,Build Tools Version 20

我希望它能有所帮助:

删除:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.notification_menu, menu);
    return true;
}

然后在您的onCreate method:中

 ActionBar mActionBar = getActionBar();
 LayoutInflater mInflater = LayoutInflater.from(this);
 View mCustomView = mInflater.inflate(R.layout.notification_switch, null);
 mActionBar.setCustomView(mCustomView);
 mActionBar.setDisplayShowCustomEnabled(true);

参考:

http://javatechig.com/android/actionbar-with-custom-view-example-in-android

如果使用actionBarCompat,请使用getSupportActionBar而不是getActionBar

最新更新