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

前端 未结 8 1980
庸人自扰
庸人自扰 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

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:fitsSystemWindows="true"
        android:minHeight="?attr/actionBarSize"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:background="?attr/colorPrimaryDark">
    </android.support.v7.widget.Toolbar>
    

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 10:18

    Add a toolbar to your xml

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fragment title"/>
    
    </android.support.v7.widget.Toolbar>
    

    Then inside your onCreateView method in the Fragment:

    Toolbar toolbar = view.findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_back_button);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             getActivity().onBackPressed();
        }
    });
    
    0 讨论(0)
  • 2020-12-02 10:28

    The easiest solution I found was to simply put that in your fragment :

    androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(getActivity(), 
    R.id.nav_host_fragment);
                navController.navigate(R.id.action_position_to_destination);
            }
        });
    

    Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

    0 讨论(0)
  • 2020-12-02 10:30

    OnToolBar there is a navigation icon at left side

    Toolbar  toolbar = (Toolbar) findViewById(R.id.tool_bar);
            toolbar.setTitle(getResources().getString(R.string.title_activity_select_event));
            setSupportActionBar(toolbar);
    
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    By using this at left side navigation icon appear and on navigation icon click it call parent activity.

    and in manifest we can notify system about parent activity.

      <activity
                android:name=".CategoryCloudSelectActivity"
                android:parentActivityName=".EventSelectionActivity"
                android:screenOrientation="portrait" />
    
    0 讨论(0)
  • 2020-12-02 10:33

    I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.

    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
                    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onBackPressed();
                        }
                    });
                } else {
                    //show hamburger
                    drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                    drawerFragment.mDrawerToggle.syncState();
                    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
                        }
                    });
                }
            }
        });
    
    0 讨论(0)
  • 2020-12-02 10:39

    Probably the cleanest solution:

    abstract class NavigationChildFragment : Fragment() {
    
        abstract fun onCreateChildView(inflater: LayoutInflater,
                                       container: ViewGroup?,
                                       savedInstanceState: Bundle?): View?
    
        override fun onCreateView(inflater: LayoutInflater,
                                  container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            val activity = activity as? MainActivity
            activity?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
            setHasOptionsMenu(true)
            return onCreateChildView(inflater, container, savedInstanceState)
        }
    
        override fun onDestroyView() {
            val activity = activity as? MainActivity
            activity?.supportActionBar?.setDisplayHomeAsUpEnabled(false)
            setHasOptionsMenu(false)
            super.onDestroyView()
        }
    
        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            val activity = activity as? MainActivity
            return when (item.itemId) {
                android.R.id.home -> {
                    activity?.onBackPressed()
                    true
                }
                else              -> super.onOptionsItemSelected(item)
            }
        }
    }
    

    Just use this class as parent for all Fragments that should support navigation.

    0 讨论(0)
提交回复
热议问题