FragNav


Source link: https://github.com/ncapdevi/FragNav

FragNav

Android library for managing multiple stacks of fragments (e.g., Bottom Navigation , Navigation Drawer). This library does NOT include the UI for bottom tab bar layout. For that, I recommend either BottomBar (which is the library shown in the demo) or AHBottomNavigation. This library helps maintain order after pushing onto and popping from multiple stacks(tabs). It also helps with switching between desired tabs and clearing the stacks.

Sample

With Material Design Bottom Navigation pattern, and other tabbed navigation, managing multiple stacks of fragments can be a real headache. The example file shows best practice for navigating deep within a tab stack.

Gradle

compile 'com.ncapdevi:frag-nav:2.2.3'

How do I implement it?

Initialize using a builder and one of two methods

builder = FragNavController.newBuilder(savedInstanceState, getSupportFragmentManager(), R.id.container);

1.

Create a list of fragments and pass them in

List<Fragment> fragments = new ArrayList<>(5);
  fragments.add(RecentsFragment.newInstance());
 fragments.add(FavoritesFragment.newInstance());
 fragments.add(NearbyFragment.newInstance());
 fragments.add(FriendsFragment.newInstance());
 fragments.add(FoodFragment.newInstance());
  builder.rootFragments(fragments);

Allow for dynamically creating the base class by implementing the NavListener in your class and overriding the getRootFragment method

public class YourActivity extends AppCompatActivity implements FragNavController.RootFragmentListener {
builder.rootFragmentListener(this, 5)
 @Override
  public Fragment getRootFragment(int index) {

switch (index) {

 case INDEX_RECENTS:

  return RecentsFragment.newInstance(0);

 case INDEX_FAVORITES:

  return FavoritesFragment.newInstance(0);

 case INDEX_NEARBY:

  return NearbyFragment.newInstance(0);

 case INDEX_FRIENDS:

  return FriendsFragment.newInstance(0);

 case INDEX_FOOD:

  return FoodFragment.newInstance(0);

}

throw new IllegalStateException("Need to send an index that we know");

  
}

3.

mFragNavController = builder.build();

SaveInstanceState

Send in the supportFragment Manager, a list of base fragments, the container that you'll be using to display fragments. After that, you have four main functions that you can use In your activity, you'll also want to override your onSaveInstanceState like so

@Override
  protected void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState);

if (mNavController != null) {

 mNavController.onSaveInstanceState(outState);

}

  
}

Switch tabs

Tab switching is indexed to try to prevent you from sending in wrong indices. It also will throw an error if you try to switch to a tab you haven't defined a base fragment for.

fragNavController.switchTab(NavController.TAB1);

Push a fragment

You can only push onto the currently selected index


  fragNavController.pushFragment(FoodFragment.newInstance())

Pop a fragment

You can only pop from the currently selected index. This can throw an UnsupportedOperationException if trying to pop the root fragment


  fragNavController.popFragment();

Pop multiple fragments

You can pop multiple fragments at once, with the same rules as above applying. If the pop depth is deeper than possible, it will stop when it gets to the root fragment


 fragNavController.popFragments(3);

Replacing a fragment

You can only replace onto the currently selected index


  fragNavController.replaceFragment(Fragment fragment);

You can also clear the stack to bring you back to the base fragment


  fragNavController.clearStack();

You can also navigate your DialogFragments using


  showDialogFragment(dialogFragment);

clearDialogFragment();

getCurrentDialogFrag()

Transaction Options

All of the above transactions can also be done with defined transaction options. The FragNavTransactionOptions have a builder that can be used.

public class FragNavTransactionOptions {

  List<Pair<View, String>> sharedElements;
  @FragNavController.Transit
  int transition = FragmentTransaction.TRANSIT_NONE;
  @AnimRes
  int enterAnimation = 0;
  @AnimRes
  int exitAnimation = 0;
  @AnimRes
  int popEnterAnimation = 0;
  @AnimRes
  int popExitAnimation = 0;
  @StyleRes
  int transitionStyle = 0;
  String breadCrumbTitle;
  String breadCrumbShortTitle;
  
}
  

Get informed of fragment transactions

Have your activity implement FragNavController.TransactionListener and you will have methods that inform you of tab switches or fragment transactions

A sample application is in the repo if you need to see how it works.

Fragment Transitions

Use FragNavController.setTransitionMode();

Helper functions

/** 
  * Get the number of fragment stacks 
  * 
  * @return the number of fragment stacks 
  */
  @CheckResult
  public int getSize()

/** 
  * Get a copy of the stack at a given index 
  * 
  * @return requested stack 
  */
  @SuppressWarnings("unchecked")
  @CheckResult
  @Nullable
  public Stack<Fragment> getStack(@TabIndex int index)

  /** 

* Get a copy of the current stack that is being displayed 

* 

* @return Current stack 

*/

@SuppressWarnings("unchecked")

@CheckResult

@Nullable

public Stack<Fragment> getCurrentStack()

 /** 

 * Get the index of the current stack that is being displayed 

 * 

 * @return Current stack index 

 */

 @CheckResult

 @TabIndex

 public int getCurrentStackIndex()

 /** 
  * @return If true, you are at the bottom of the stack 
  * (Consider using replaceFragment if you need to change the root fragment for some reason) 
  * else you can popFragment as needed as your are not at the root 
  */
  @CheckResult
  public boolean isRootFragment()

  /** 

* @return Current DialogFragment being displayed. Null if none 

*/

@Nullable

@CheckResult

public DialogFragment getCurrentDialogFrag()
  

Apps Using FragNav

Feel free to send me a pull request with your app and I'll link you here:

Contributions

If you have any problems, feel free to create an issue or pull request.

The sample app in the repository uses BottomBar library.

License

FragNav Android Fragment Navigation Library Copyright (c) 2016 Nic Capdevila (http://github.com/ncapdevi).  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

A beautiful, fluid, and customizable dialogs API.
This is an android popup library "BlankSpace".
An Android Kotlin library for fully customizable Snackbars

Apache Oltu is an OAuth protocol implementation in Java. It also covers others "OAuth family" related implementations such as JWT, JWS and OpenID Connect.

A collection of buttons for use in Android applications.

kXML2 (or a compatible XML pull parser) should be available on all Android devices.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes