I'm trying to use a SwitchCompat
widget on the overflow menu of android.support.v7.widget.Toolbar
but I just can't get it to work, it always appears blank.
Here is my menu definition:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.oveflowtest.ScrollingActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
<item android:id="@+id/test"
app:actionLayout="@layout/testlayout"
app:showAsAction="never"/>
</menu>
And here is testlayout
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="match_parent" android:text="test"/>
</LinearLayout>
Also if I change showAsAction
to always
instead of never
then it shows just fine on the toolbar but I don't want it there, I want it on the overflow menu that opens up when I press the 3 dots.
I know there is an option to use a checkmark but the design I'm following calls for a switch.
Thanks.
It's not possible.
That's because actionLayout
is used only when the item is shown as action. It's equivalent to setActionView
and, from the documentation:
Set an action view for this menu item. An action view will be displayed in place of an automatically generated menu item element in the UI when this item is shown as an action within a parent.
So, you can inflate a custom view if it's used as an action (if showAsAction
is never
, then it's not shown as action, as expected).
Now, hidden somewhere else, in the documentation for ActionProvider
, there's this:
When the menu item is presented in a way that does not allow custom action views, (e.g. in an overflow menu,) the ActionProvider can perform a default action.
It's explicitly stated that overflow menu can't display custom view.
[Edit: possible workaround]
If you really want to display it that way, you can fake an overflow menu with PopupWindow
, but then you may lose consistency with the platform in some devices or even after an upgrade to Android (let's say… you used three round dots to simulate the overflow menu, but later it is changed back to squares on Android, your app will look odd. There's also the extra effort to make it work while with a Menu
it would be straightforward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With