hotwired / turbo-android

Android framework for making Turbo native apps
MIT License
423 stars 51 forks source link

Add menu options to custom menu in WebFragment #228

Closed annajeanine closed 2 years ago

annajeanine commented 2 years ago

I have extended the res/menu/web with a logout option:

<?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"
    xmlns:tools="http://schemas.android.com/tools">

    <item
        android:id="@+id/menu_progress"
        android:title="@string/loading"
        android:visible="false"
        app:actionLayout="@layout/toolbar_progress"
        app:showAsAction="always"
        tools:ignore="AlwaysShowAction" />

    <item
        android:id="@+id/logoutButton"
        android:title="Logout"
        app:showAsAction="always"/>
</menu>

In the WebFragment I want to handle the logout, but the action is not being called. I'm trying this by doing:

    private fun setupMenu() {
        toolbarForNavigation()?.inflateMenu(R.menu.web)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        Log.d("WebFragment", "Options item selected")

        return when (item.itemId) {
            R.id.logoutButton -> {
                Log.i("WebFragment", "Logout button pressed")
                requireActivity().startNewActivity(PasswordActivity::class.java)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

I have tried solving this by checking this StackOverflow topic, but no luck. Therefor, I am wondering if it is even possible with this package.

jayohms commented 2 years ago

The turbo-android library doesn't handle menu items in any direct way, but it's totally supported in your own app and custom code. You'll want to handle it similar to this:

toolbarForNavigation()?.apply {
    inflateMenu(R.menu.web)
    setOnMenuItemClickListener {
        when (it.itemId) {
            R.id.logoutButton -> {
                // ...
                true
            }
            else -> false
        }
    }
}

This is a more modern approach using the Toolbar APIs directly than overriding onOptionsItemSelected().

annajeanine commented 2 years ago

@jayohms Thank you! Works like a charm :)