I am using Navigation Architecture Component with androidx.
I would like to add a menu icon on the right of the navigation bar ONLY on one of my child fragments.
Is it possible ? What do i miss ? Here is my first test code implementation :
my_menu.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">
<item
android:id="@+id/optionIconId"
android:icon="@drawable/option_icon"
android:visible="true"
app:showAsAction="ifRoom|withText"/>
</menu>
TestFragment.kt
class TestFragment : Fragment() {
/**
* Fragment binding.
*/
private var _binding: FragmentTestBinding? = null
/**
* Fragment binding.
*/
private val binding get() = this._binding!!
/**
* @inheritdocs
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
this._binding = FragmentTestBinding.inflate(inflater, container, false)
return this.binding.root
}
/**
* @inheritdocs
*/
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.optionIconId).isVisible = true
super.onPrepareOptionsMenu(menu)
}
/**
* @inheritdocs
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.optionIconId -> {
println("CLICK CLICK CLICK")
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
fragment_test.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can manage this behavior from your current fragment or activity. You need to create one toolbar for all fragments (in your activity) and managed menu visibility there with navigation changed callback, or create toolbars for each fragment with different menu.