Cannot get Switch menu item because R.id.* is different from menu items' internal ids

半城伤御伤魂 提交于 2020-07-10 10:28:38

问题


I am not able to use setOnCheckedChangeListener because getting a Switch menu item by id won't work as the resource id is different from the menu id.

This is what I've got:

Toolbar

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
    android:elevation="4dp"
    android:id="@+id/toolbar"
    app:title="Toolbar">

</androidx.appcompat.widget.Toolbar>

Menu items with the Switch

<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.hedev.linguist.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/app_bar_review_switch"
        android:actionLayout="@layout/switch_item"
        android:title="Switch"
        app:showAsAction="always"
        app:actionViewClass="android.widget.Switch" />
</menu>

The Switch itself

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Switch
        android:id="@+id/review_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

I activate it onCreate with setSupportActionBar(toolbar) and it shows correctly. Then I want to wire the event handler with

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)

        (menu?.findItem(R.id.app_bar_review_switch) as Switch)?.setOnCheckedChangeListener { buttonView, isChecked ->
            println("Switch!")
        }

        return true
    }

but no matter what I do, it cannot find the Switch by its id. I've checked the internal array with the menu-items of the menu and both items are there. I could get them with getItem and use an index but I prefer to use the ids if only they weren't different. When I check the R.id.app_bar_review_switch in the debugger, it's like 1000289 and when I look inside the internal menu array then the item there has the id like 2131296330. Why are they different? What do I miss here?

I use API Level 28

来源:https://stackoverflow.com/questions/61986180/cannot-get-switch-menu-item-because-r-id-is-different-from-menu-items-interna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!