[android] How to get Toolbar from fragment?

I have ActionBarActivity with NavigationDrawer and use support_v7 Toolbar as ActionBar. In one of my fragments toolbar has custom view. In other fragments Toolbar should show title.

How get Toolbar instance for customizing from fragments? I can get ActionBar with getActivity().getActionBar(), but if I call setTitle() for this instance ActionBar it do nothing.

UPD:

In my case

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle();

(as MrEngineer13 said) don't work at first fragment creation because I call it from onHiddenChanged(). Now I add more one to onCreateView() and it works fine.

The answer is


In XML

 <androidx.appcompat.widget.Toolbar
  android:id="@+id/main_toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:layout_scrollFlags="scroll|enterAlways">
 </androidx.appcompat.widget.Toolbar>

Kotlin: In fragment.kt -> onCreateView()

setHasOptionsMenu(true)

val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)

(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)

(activity as? AppCompatActivity)?.supportActionBar?.show()

-> onCreateOptionsMenu()

   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.app_main_menu,menu)
       super.onCreateOptionsMenu(menu, inflater)
   }

->onOptionsItemSelected()

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.selected_id->{//to_do}
             else -> super.onOptionsItemSelected(item)
        }
    }

You have two choices to get Toolbar in fragment

First one

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

and second one

Toolbar toolbar = ((MainActivity) getActivity()).mToolbar;

toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below.

MainActivity activity = (MainActivity) getActivity();

then use activity for further implementation like below

ImageView vRightBtn = activity.toolbar.findViewById(R.id.toolbar_right_btn);

Before calling this, you need to initialize your custom toolbar in your MainActivity as below.

First set define your toolbar public like

public Toolbar toolbar;
public ActionBar actionBar;

and in onCreate() Method assign the custom toolbar id

toolbar = findViewById(R.id.custom_toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();

That's It. It will work in Fragment.


From your Fragment: ( get Toolbar from fragment?)

// get toolbar
((MainAcivity)this.getActivity()).getToolbar();  // getToolbar will be method in Activity that returns Toolbar!!  don't use getSupportActionBar for getting toolbar!!
// get action bar
this.getActivity().getSupportActionBar();

this is very helpful when you are using spinner in Toolbar and call the spinner or custom views in Toolbar from a fragment!

From your Activity:

// get toolbar
this.getToolbar();
// get Action Bar
this.getSupportActionBar();

In case fragments should have custom view of ToolBar you can implement ToolBar for each fragment separately.

add ToolBar into fragment_layout:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"/>

find it in fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        //set toolbar appearance
        toolbar.setBackground(R.color.material_blue_grey_800);

        //for crate home button
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

menu listener could be created two ways: override onOptionsItemSelected in your fragment:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
        case android.R.id.home:
            getActivity().onBackPressed();
    }
    return super.onOptionsItemSelected(item);
}

or set listener for toolbar when create it in onCreateView():

toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                return false;
            }
        });

Maybe you have to try getActivity().getSupportActionBar().setTitle() if you are using support_v7.


For Kotlin users (activity as AppCompatActivity).supportActionBar?.show()


I did it by using these steps.

  1. Set Title using below code in onCreateView of the main fragment.
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your title");

  1. For swapping between fragments i'm using bottom navigation bar which is implemented on MainActivity (Parent Activity) of the fragment. Even if you are using any button or menu item then you can change the title from onSelectedItemClickListener, just like i did in my case.
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.menu_dashboard:
                getSupportActionBar().setTitle("Dashboard");
                fm.beginTransaction().hide(active).show(dashboardFragment).commit();
                active = dashboardFragment;
                return true;
            case R.id.menu_workshop:
                getSupportActionBar().setTitle("Workshops");
                fm.beginTransaction().hide(active).show(workshopFragment).commit();
                active = workshopFragment;
                return true;
         }
         return false;
    }
    

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to android-actionbar

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? Failed to load AppCompat ActionBar with unknown error in android studio Android transparent status bar and actionbar ActionBarActivity is deprecated Manage toolbar's navigation and back button from fragment in android setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error How to use SearchView in Toolbar Android How to get Toolbar from fragment? Display Back Arrow on Toolbar Remove title in Toolbar in appcompat-v7

Examples related to android-support-library

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0 Failed to resolve: com.android.support:cardview-v7:26.0.0 android Setting up Gradle for api 26 (Android) How to make ConstraintLayout work with percentage values? Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio Change EditText hint color when using TextInputLayout Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized? Error inflating class android.support.design.widget.NavigationView FloatingActionButton example with Support Library How to use and style new AlertDialog from appCompat 22.1 and above

Examples related to android-toolbar

Add views below toolbar in CoordinatorLayout Creating a button in Android Toolbar Android transparent status bar and actionbar Manage toolbar's navigation and back button from fragment in android How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)? Toolbar Navigation Hamburger Icon missing How to use SearchView in Toolbar Android How to get Toolbar from fragment? How to add buttons like refresh and search in ToolBar in Android? Change status bar color with AppCompat ActionBarActivity