项目作者: sergiormg

项目描述 :
Using toolbars within fragments
高级语言: Java
项目地址: git://github.com/sergiormg/ToolbarFromFragment.git
创建时间: 2017-03-21T23:35:07Z
项目社区:https://github.com/sergiormg/ToolbarFromFragment

开源协议:

下载


ToolbarFromFragment

Build Status

Using toolbars within fragments.

Imagine you have an application that uses the navigation drawer and each fragment has their own toolbar. When you change fragment the toolbar will change accordingly:

  1. <android.support.v7.widget.Toolbar
  2. android:id="@+id/toolbar"
  3. app:title="@string/first_fragment"
  4. android:layout_width="match_parent"
  5. android:layout_height="?attr/actionBarSize"
  6. android:background="?attr/colorPrimary"
  7. app:popupTheme="@style/AppTheme.PopupOverlay" ></android.support.v7.widget.Toolbar>

To do that, first you need to set the new toolbar in your fragment during onCreateView:

  1. ((AppCompatActivity) getActivity()).setSupportActionBar((Toolbar) view.findViewById(R.id.toolbar));

And then, in your activity, you need to execute some code to make sure that your toolbar deal with the navigation drawer:

  1. // Restores the behaviour of action bar and ActionBarDrawerToggle
  2. ActionBar actionBar = getSupportActionBar();
  3. if (actionBar != null) {
  4. actionBar.setDisplayHomeAsUpEnabled(true);
  5. actionBar.setHomeButtonEnabled(true);
  6. }
  7. mDrawerToggle = new ActionBarDrawerToggle(
  8. this,
  9. mDrawerLayout,
  10. R.string.navigation_drawer_open,
  11. R.string.navigation_drawer_close
  12. ) {
  13. @Override
  14. public void onDrawerOpened(View drawerView) {
  15. super.onDrawerOpened(drawerView);
  16. }
  17. };
  18. // Synchronizes the state of the drawer indicator with the DrawerLayout
  19. mDrawerLayout.post(new Runnable() {
  20. @Override
  21. public void run() {
  22. mDrawerToggle.syncState();
  23. }
  24. });
  25. mDrawerLayout.addDrawerListener(mDrawerToggle);

Check out the full example to test how it works!