toolbar in fragment android kotlin

To add a toolbar in a fragment using Kotlin in Android, you can follow these steps:

  1. In your fragment's XML layout file, add the Toolbar widget. You can do this by adding the following code:
<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />
  1. In your fragment's Kotlin code, initialize the Toolbar object. You can do this by adding the following code in the onCreateView method:
val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
  1. Set the Toolbar as the support action bar for the fragment. You can do this by adding the following code:
(requireActivity() as AppCompatActivity).setSupportActionBar(toolbar)
  1. Customize the Toolbar as needed. You can add a title, set navigation icons, or add menu items. Here are a few examples:

To set the title:

(requireActivity() as AppCompatActivity).supportActionBar?.title = "Fragment Title"

To set a navigation icon:

toolbar.setNavigationIcon(R.drawable.ic_back)
toolbar.setNavigationOnClickListener {
    // Handle navigation icon click here
}

To add menu items:

toolbar.inflateMenu(R.menu.menu_fragment)
toolbar.setOnMenuItemClickListener { item ->
    when (item.itemId) {
        R.id.menu_item1 -> {
            // Handle menu item 1 click here
            true
        }
        R.id.menu_item2 -> {
            // Handle menu item 2 click here
            true
        }
        else -> false
    }
}

That's it! You have successfully added a toolbar in a fragment using Kotlin in Android. Feel free to customize it further based on your requirements.