49

I need to use the setSupportActionBar in fragment which I am unable to also I am unable to use setContentView please to help with it also Thankyou in advance the related code is given

public class StudentrFragment extends Fragment {
        Toolbar toolbar;
        TabLayout tabLayout;
        ViewPager viewPager;
        ViewPagerAdapter viewPagerAdapter;


        public StudentrFragment() {
            // Required empty public constructor
        }


        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.tabbar_layout);
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar); 
            tabLayout = (TabLayout) findViewById(R.id.tabLayout);
            viewPager = (ViewPager) findViewById(R.id.viewPager);
            viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
            viewPagerAdapter.addFragments(new CivilFragment(),"Civil Dept");
            viewPagerAdapter.addFragments(new ComputerFragment(),"CSE Dept");
            viewPagerAdapter.addFragments(new EeeFragment(),"EEE Dept");
            viewPagerAdapter.addFragments(new EceFragment(),"ECE Dept");
            viewPager.setAdapter(viewPagerAdapter);
            tabLayout.setupWithViewPager(viewPager);

        }

    }
  • 2
    Possible duplicate of [How to use Android AppBarLayout, Toolbar and TabLayout with fragments](http://stackoverflow.com/questions/32326248/how-to-use-android-appbarlayout-toolbar-and-tablayout-with-fragments) – Farhad Jul 04 '16 at 16:47

5 Answers5

152

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;
}
Mustansir
  • 2,445
  • 1
  • 21
  • 32
  • Is it maybe a good idea to wrap it in: `if (getActivity() instanceof AppCompatActivity){//start using it as AppCompatActivity}`. Because you don't know how/where people use your fragment? – Tanasis Nov 28 '18 at 09:37
  • 1
    If you extend a support fragment, it will for sure be used in a support (AppCompat) activity, especially now with the AndroidX changes. If you really want to check (but there should be no need), `(activity as? AppCompatActivity)?.setSupportActionBar(myToolbar)` does it. – milosmns Sep 29 '19 at 16:28
10

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.

Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123
  • Hi Valeriy, I took a look at your example and the menu seems to inflate nicely. Where would you suggest to place the code that handles menu option selection? Since in this way the `onOptionsItemSelected` method is not called anymore. – Wafje Jan 23 '21 at 22:39
  • 1
    @Wafje Please take a look at the updated example, hope it helps! – Valeriy Katkov Jan 24 '21 at 09:29
  • 1
    Worked perfectly, thanks to your example I also found the related [documentation](https://developer.android.com/guide/fragments/appbar#fragment-click) – Wafje Jan 24 '21 at 12:12
1

This site has the solution which worked for me!

Pasting it:

toolbar = (Toolbar) getView().findViewById(R.id.toolbar);

AppCompatActivity activity = (AppCompatActivity) getActivity();

activity.setSupportActionBar(toolbar);
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

Setup support action bar for navigation menu in Kotlin :

(activity as AppCompatActivity?)!!.setSupportActionBar(customToolbar as Toolbar?)

Also to animate the hamburger icon at the toggle of DrawerLayout :

val actionBarDrawerToggle: ActionBarDrawerToggle = object : ActionBarDrawerToggle(activity,
                drawer_layout, customToolbar as Toolbar?, R.string.open_drawer, R.string.close_drawer) { }
    
drawer_layout.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
Mudit Goel
  • 196
  • 1
  • 5
0

In your fragment's onCreateView function add this:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        //Set toolbar
        val view: View = inflater.inflate(R.layout.*enter the fragment containing toolbar here*, container, false)
        val toolbar: Toolbar = view.findViewById<Toolbar>(R.id.toolbar)
        (requireActivity() as AppCompatActivity).setSupportActionBar(toolbar)
        return view
    }
The_Vinci
  • 1
  • 1