FastAdapter


Source link: https://github.com/mikepenz/FastAdapter

FastAdapter

The RecyclerView is one of the most used widgets in the Android world, and with it you have to implement an Adapter which provides the items for the view. Most use cases require the same base logic, but require you to write everything again and again.

The FastAdapter is here to simplify this process. You don't have to worry about the adapter anymore. Just write the logic for how your view/item should look like, and you are done. This library has a fast and highly optimized core which provides core functionality, most apps require. It also prevents common mistakes by taking away those steps from the devs. Beside being blazing fast, minimizing the code you need to write, it is also really easy to extend. Just provide another adapter implementation, hook into the adapter chain, custom select / deselection behaviors. Everything is possible.

A quick overview:

Preview

Demo

You can try it out here Google Play (or download the latest release from GitHub)

Screenshots

Include in your project

Using Maven

The library is split up into core, commons, and extensions. The core functions are included in the following dependency.

implementation 'com.mikepenz:fastadapter:3.0.1@aar' implementation  'com.android.support:appcompat-v7:${
latestSupportLib
}
' implementation  'com.android.support:recyclerview-v7:${
latestSupportLib
}
'

The commons package comes with some useful helpers (which are not needed in all cases) This one for example includes the FastItemAdapter

implementation 'com.mikepenz:fastadapter-commons:3.0.1@aar'

Expandable support is included and can be added via this

implementation 'com.mikepenz:fastadapter-extensions-expandable:3.0.0@aar' //The tiny Materialize library used for its useful helper classes implementation 'com.mikepenz:materialize:${
latestVersion
}
@aar'

Many helper classes are included in the following dependency. (This functionality also needs the Expandable extension

implementation 'com.mikepenz:fastadapter-extensions:3.0.0@aar' implementation  'com.android.support:design:${
versions.supportLib
}
' //The tiny Materialize library used for its useful helper classes implementation 'com.mikepenz:materialize:${
latestVersion
}
@aar'

v3.0.x

v3 is a huge new release and comes with a big set of new changes. If you previously used the FastAdapter and head over to the MIGRATION GUIDE on how to get started with v3. In case you are searching v2.x head over here to it here.

How to use

1. Implement your item (the easy way)

Just create a class which extends the AbstractItem as shown below. Implement the methods, and your item is ready.

public class SimpleItem extends AbstractItem<SimpleItem, SimpleItem.ViewHolder> {

  public String name;
  public String description;

//The unique ID for this type of item
  @Override
  public int getType() {

return R.id.fastadapter_sampleitem_id;
  
}

//The layout to be used for this type of item
  @Override
  public int getLayoutRes() {

return R.layout.sample_item;
  
}

@Override
  public ViewHolder getViewHolder(@NonNull View v) {

return new ViewHolder(v);

  
}

/** 
  * our ViewHolder 
  */
  protected static class ViewHolder extends FastAdapter.ViewHolder<SimpleItem> {

@BindView(R.id.material_drawer_name)

TextView name;

@BindView(R.id.material_drawer_description)

TextView description;

 public ViewHolder(View view) {

 super(view);

 ButterKnife.bind(this, view);

}

 @Override

public void bindView(SimpleItem item, List<Object> payloads) {

 StringHolder.applyTo(item.name, name);

 StringHolder.applyToOrHide(item.description, description);

}

 @Override

public void unbindView(SimpleItem item) {

 name.setText(null);

 description.setText(null);

}

  
}
 
}

2. Set the Adapter to the RecyclerView

//create the ItemAdapter holding your Items ItemAdapter itemAdapter = new ItemAdapter();
 //create the managing FastAdapter, by passing in the itemAdapter FastAdapter fastAdapter = FastAdapter.with(itemAdapter);
  //set our adapters to the RecyclerView recyclerView.setAdapter(fastAdapter);
  //set the items to your ItemAdapter itemAdapter.add(ITEMS);

3. Click listener

fastAdapter.withSelectable(true);
 fastAdapter.withOnClickListener(new OnClickListener<Item>() {

  @Override
  public boolean onClick(View v, IAdapter<Item> adapter, Item item, int position) {

  // Handle click here  return true;
  
}
 
}
);

4. Click listeners for views inside your item

//just add an `EventHook` to your `FastAdapter` by implementing either a `ClickEventHook`, `LongClickEventHook`, `TouchEventHook`, `CustomEventHook` fastItemAdapter.withEventHook(new ClickEventHook<SampleItem>() {

 @Nullable
  @Override
  public View onBind(@NonNull RecyclerView.ViewHolder viewHolder) {

//return the views on which you want to bind this event

if (viewHolder instanceof SampleItem.ViewHolder) {

 return ((ViewHolder) viewHolder).view;

}

return null;
  
}

@Override
  public void onClick(View v, int position, FastAdapter<SampleItem> fastAdapter, SampleItem item) {

//react on the click event
  
}
 
}
);

5. Filter

// Call this in onQueryTextSubmit() & onQueryTextChange() when using SearchView fastAdapter.filter("yourSearchTerm");
  fastAdapter.getItemFilter().withFilterPredicate(new IItemAdapter.Predicate<Item>() {

  @Override
  public boolean filter(Item item, CharSequence constraint) {
  return item.getName().startsWith(String.valueOf(constraint));

  
}
 
}
);

filter() will return true to indicate which items will be removed. Returning false indicates items that will be retained.

6. Drag and drop

First, attach ItemTouchHelper to RecyclerView.

SimpleDragCallback dragCallback = new SimpleDragCallback(this);
 ItemTouchHelper touchHelper = new ItemTouchHelper(dragCallback);
 touchHelper.attachToRecyclerView(recyclerView);

Implement ItemTouchCallback interface in your Activity, and override the itemTouchOnMove() method.

@Override
 public boolean itemTouchOnMove(int oldPosition, int newPosition) {

  Collections.swap(fastAdapter.getAdapterItems(), oldPosition, newPosition);
 // change position

  fastAdapter.notifyAdapterItemMoved(oldPosition, newPosition);

  return true;
 
}

7. Using different ViewHolders (like HeaderView)

Start by initializing your adapters:

// Head is a model class for your header ItemAdapter<Header> headerAdapter = new ItemAdapter<>();

Initialize a Model FastAdapter:

ItemAdapter<IItem> itemAdapter = new ItemAdapter<>();

Finally, set the adapter:

FastAdapter fastAdapter = FastAdapter.with(headerAdapter, itemAdapter);
 //the order defines in which order the items will show up recyclerView.setAdapter(fastAdapter);

8. Infinite (endless) scrolling

Create a FooterAdapter. We need this to display a loading ProgressBar at the end of our list. (Don't forget to pass it into FastAdapter.with(..))

ItemAdapter<ProgressItem> footerAdapter = new ItemAdapter<>();

Keep in mind that ProgressItem is provided by FastAdapter’s extensions.

recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(footerAdapter) {

  @Override
  public void onLoadMore(int currentPage) {
  footerAdapter.clear();
  footerAdapter.add(new ProgressItem().withEnabled(false));
  // Load your items here and add it to FastAdapter  fastAdapter.add(NEWITEMS);

  
}
 
}
);

For the complete tutorial and more features such as multi-select and CAB check out the sample app.

Advanced Usage

Proguard

  • As of v2.5.0 there are no more known requirements to use the FastAdapter with Proguard

ExpandableItems

The FastAdapter comes with support for expandable items. After adding the dependency set up the Expandable extension via:

expandableExtension = new ExpandableExtension<>();
 fastAdapter.addExtension(expandableExtension);

Expandable items have to implement the IExpandable interface, and the sub items the ISubItem interface. This allows better support. The sample app provides sample implementations of those. (Those in the sample are kept Model which allows them to be used with different parent / subitems)

As of the way how SubItems and their state are handled it is highly recommended to use the identifier based StateManagement. Just add withPositionBasedStateManagement(false) to your FastAdapter setup.

A simple item just needs to extend from the AbstractExpandableItem and provide the Parent, the ViewHolder and the SubItems it will contain as type.

public class SimpleSubExpandableItem extends AbstractExpandableItem<SimpleSubExpandableItem, SimpleSubExpandableItem.ViewHolder, SubItem> {

/** 
  * BASIC ITEM IMPLEMENTATION 
  */ 
}

Articles

Libs used in sample app:

Mike Penz:

Other Libs:

Developed By

Contributors

This free, open source software was also made possible by a group of volunteers that put many hours of hard work into it. See the CONTRIBUTORS.md file for details.

Special mentions

I want to give say thanks to some special contributors who provided some huge PRs and many changes to improve this great library.

License

Copyright 2017 Mike Penz  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

SQLiteToExcel is a light weight library to convert SQLite database to Excel.

A small library to show share buttons panel with CoordinatorLayout.

Better Video Player is a rethought version(fork) of Easy Video Player

Better Video Player supports captions through subtitles in 2 formats: SRT and WEBVTT.

Volume and track position control with swipe gestures are usually supported by mostly used media players like VLC or MX Player. This feature lets your users to be familiar with your video player. For now, this option cannot be disabled but this will be possible in the future.

This is a simple example for booking movie seats in general movie/film mobile application. The concept is simply combined of State Design Pattern, Android Data Binding and Multibinding + Autofactory below.

Small solution that gives you the easy way to implement customized slide-to-unlock view into your app. SlideLayout provides additional methods and classes for changing component's behavior and appearance: various orientations, transitions, directions etc.

Just a beautiful action bar.

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