Sulaiman Abdul Quadeer
Sulaiman Abdul Quadeer

Reputation: 581

how to use setSupportActionBar in fragment

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);

        }

    }

Upvotes: 50

Views: 68960

Answers (5)

The_Vinci
The_Vinci

Reputation: 1

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
    }

Upvotes: 0

Mudit Goel
Mudit Goel

Reputation: 354

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()

Upvotes: 2

NewCoder1423
NewCoder1423

Reputation: 55

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);

Upvotes: 1

Valeriy Katkov
Valeriy Katkov

Reputation: 40752

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.

Upvotes: 10

Mustansir
Mustansir

Reputation: 2515

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;
}

Upvotes: 155

Related Questions