Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle drawer toggle and toolbar up when having toolbar for each fragment

I am using single activity and many fragments approach in my app

Now since in my some fragments I have custom view in toolbar I decided to have separate toolbar for each fragment.

How to implement separate toolbar for each fragment also the drawer layout is in my activity Home page category page

like image 456
alphanso Avatar asked Dec 11 '17 19:12

alphanso


People also ask

How to set toolbar in fragment?

To do this, call setHasOptionsMenu(true) in the onCreate() method of the fragment. The Android framework calls in this case the onCreateOptionsMenu() method in the fragment class. Here the fragment can adds menu items to the toolbar.

How do I access the activity toolbar in fragment?

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. ImageView vRightBtn = activity. toolbar.


1 Answers

I have the same problem, I will add custom toolbar view for each fragment.

My Utility method is:

public static View addRemoveViewFromToolbar(FragmentActivity fragmentActivity, int resourceId) {
    Toolbar toolbar = removeViewFromToolbar(fragmentActivity);
    if (resourceId == 0) {
        return null;
    } else {
        View view = LayoutInflater.from(fragmentActivity).inflate(resourceId, toolbar, false);
        toolbar.addView(view);
        return view;
    }
}


public static Toolbar removeViewFromToolbar(FragmentActivity fragmentActivity) {
    Toolbar toolbar = (Toolbar) fragmentActivity.findViewById(R.id.toolbar);
    if (toolbar.getChildCount() > 1) {
        for (int i = 1; i <= toolbar.getChildCount(); i++) {
            toolbar.removeViewAt(1);
        }
    }
    return toolbar;
}

In my each fragment

//Create your custom view based on requirement
    View view = Utility.addRemoveViewFromToolbar(getActivity(), R.layout.toolbar_search_view);
        if (view != null) {
            edtCategory1 = (EditText) view.findViewById(R.id.edtCategory1);
            edtCategory1.setOnClickListener(this);
        }

Hope this explanation help you :)

like image 179
Mitesh Vanaliya Avatar answered Nov 15 '22 16:11

Mitesh Vanaliya