Android Create Option Menu From Fragment (Kotlin)

Fragment code.

class TestFragment : Fragment() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setHasOptionsMenu(true)    }    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {        inflater.inflate(R.menu.menu_test, menu);        super.onCreateOptionsMenu(menu, inflater)    }    override fun onOptionsItemSelected(item: MenuItem): Boolean {        return (when(item.itemId) {            R.id.action_test -> {                true            }            else ->                super.onOptionsItemSelected(item)        })    }}

Menu resource 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"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.luasoftware.test.MainActivity">

    <item
        android:id="@+id/action_test"
        android:orderInCategory="100"
        android:title="Test"
        app:showAsAction="ifRoom" />

</menu>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.