how to use setSupportActionBar in fragment

Solution 1:

You can setSupportActionbar like this in fragments:

((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);

You need to inflate tabbar_layout in onCreateView of Fragment. Like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabbar_layout, container, false);
 //YOUR STUFF
return rootView;
}

Solution 2:

The suggested solution works, but it doesn't look elegant, ideally a fragment shouldn't know anything about its parent activity. An alternative might be not to use setSupportActionBar at all. If you use navigation library it might be easier to add a Toolbar to the fragment layout and setup it using NavigationUI, for example:

<!-- my_fragment.xml -->
<androidx.constraintlayout.widget.ConstraintLayout ... >

  <com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/toolbar"
    app:menu="@menu/my_fragment_menu"
    ... />

</androidx.constraintlayout.widget.ConstraintLayout>
class MyFragment : Fragment() {
  ...

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val navController = findNavController()
    binding.toolbar.setupWithNavController(navController)

    binding.toolbar.setOnMenuItemClickListener {
      when (it.itemId) {
        // these ids should match the item ids from my_fragment_menu.xml file
        R.id.edit -> {
          Log.i("MyFragment", "edit menu item is clicked")

          // by returning 'true' we're saying that the event 
          // is handled and it shouldn't be propagated further
          true
        }
        else -> false
      }
    }

    // if you prefer not to use xml menu file 
    // you can also add menu items programmatically
    val shareMenuItem = binding.toolbar.menu.add(R.string.share)
    shareMenuItem.setOnMenuItemClickListener {
      Log.i("MyFragment", "share menu item is clicked")
      true
    }
  }
}

You can find the full GitHub example here. Also take a look at another question Is setSupportActionbar required anymore? and my answer for more details.