Manage toolbar's navigation and back button from fragment in android

前端 未结 8 2051
庸人自扰
庸人自扰 2020-12-02 10:00

All of my fragments are controlled through ActionBarActivity (mainActivity), inside mainActivity a DrawerLayout is implemented and all the child fr

8条回答
  •  无人及你
    2020-12-02 10:17

    You can use Toolbar inside the fragment and it is easy to handle. First add Toolbar to layout of the fragment

    
    
    

    Inside the onCreateView Method in the fragment you can handle the toolbar like this.

     Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
     toolbar.setTitle("Title");
     toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
    

    IT will set the toolbar,title and the back arrow navigation to toolbar.You can set any icon to setNavigationIcon method.

    If you need to trigger any event when click toolbar navigation icon you can use this.

     toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //handle any click event
        });
    

    If your activity have navigation drawer you may need to open that when click the navigation back button. you can open that drawer like this.

     toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });
    

    Full code is here

     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //inflate the layout to the fragement
        view = inflater.inflate(R.layout.layout_user,container,false);
    
        //initialize the toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        toolbar.setTitle("Title");
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //open navigation drawer when click navigation back button
                DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });
        return view;
    }
    

提交回复
热议问题