In XML
<androidx.appcompat.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways">
</androidx.appcompat.widget.Toolbar>
Kotlin: In fragment.kt -> onCreateView()
setHasOptionsMenu(true)
val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)
(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)
(activity as? AppCompatActivity)?.supportActionBar?.show()
-> onCreateOptionsMenu()
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.app_main_menu,menu)
super.onCreateOptionsMenu(menu, inflater)
}
->onOptionsItemSelected()
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.selected_id->{//to_do}
else -> super.onOptionsItemSelected(item)
}
}