FlexAdapter


Source link: https://github.com/ajalt/flexadapter

Define and coordinate multiple layouts in a RecyclerView or ViewPager without boilerplate.

  • Multiple item layouts in a single adapter with no typecasting.
  • Per-item span, swipe, and drag behavior in a RecyclerView in just a few lines of code.
  • Add, remove, and update multiple layouts in a ViewPager without touching Fragments.

Usage

The examples will be in Kotlin, but this library works just as well with Java.

Create the adapter:

// Create the adapter val adapter = FlexAdapter<Any>() recyclerView.adapter = adapter val layoutManager = GridLayoutManager(this, 3) // Add this line to enable per-item spans on GridLayoutManagers layoutManager.spanSizeLookup = adapter.spanSizeLookup recyclerView.layoutManager = layoutManager

Define your item types:

// This item will be a text header with a span of three that can be swiped horizontally to dismiss. class TextItem(var text: String) :

FlexAdapterExtensionItem(R.layout.item_text, span = 3, swipeDirs = HORIZONTAL) {

  override fun bindItemView(itemView: View, position: Int) {

itemView.text_view.text = text
  
}
 
}
  // This will be a picture loaded from a resource the can be reordered by dragging in any direction. class PictureItem(@DrawableRes val imageRes: Int) :

FlexAdapterExtensionItem(R.layout.item_picture, dragDirs = ALL_DIRS) {

  override fun bindItemView(itemView: View, position: Int) {

itemView.image_view.setImageResource(imageRes)
  
}
 
}

Each layout in the adapter gets its own item class, which has fields for any mutable data in its layout. Since the items own the data and know how to bind it to a view holder, there are no intermediate data holder classes, no interfaces, and no casting to a base class and back.

Using your own data models

If you're using Kotlin, you don't even need your items to inherit from FlexAdapterItem. You can register a view binder for each type you'd like to add instead:

val adapter = FlexAdapter<String>() adapter.register<String>(R.layout.text_layout) {
 str, view, position ->
  view.text_view.text = str 
}
 adapter.add("title")

You can use register in the same adapter that you add FlexAdapterItems, pick whichever method you prefer.

Then add some items:

adapter.items.addAll(listOf(
  TextItem("Look at these pictures"),
  PictureItem(R.drawable.picture_1),
  PictureItem(R.drawable.picture_2) ))

All structural changes to the items list automatically updated the RecyclerView. No need to call noifyItemRangeAdded.

Update an existing item:

// If we added this TextItem earlier textItem.text = "Look at this new text" adapter.notifyItemChanged(textItem)

When you want to update an item, just change its data and notify the adapter that it changed.

That's it. No managing indices. No casting from interfaces or Object. Just fast, simple code that does exactly what you want.

Item selection

FlexAdapter can manage a set of selected items and pass the selection state to your view binders. Just inherit from FlexAdapterSelectableItem or use the register overload that takes the boolean selection state.

class PictureItem(@DrawableRes val imageRes: Int) :

FlexAdapterSelectableExtensionItem(R.layout.item_picture, dragDirs = ALL_DIRS) {

  override fun bindItemView(itemView: View, selected:Boolean, position: Int) {

itemView.image_view.setImageResource(imageRes)

itemView.switch.selected = selected
  
}
 
}
  adapter.register<String>(R.layout.item_text) {
 str, view, selected, position ->
  view.text_view.text = str
  view.switch.selected = selected 
}
  adapter.add(PictureItem(R.drawable.image)) adapter.add("Title")  adapter.selectItem("Title")

API Documentation

API documentation is hosted online here.

Sample project

To see more of the features of FlexAdapter in use, check out the Kotlin sample app here, or the Java sample app here

FlexAdapter for a ViewPager

This library also includes an adapter for a ViewPager that provides the same interface as the regular FlexAdapter: the FlexPagerAdapter

val adapter = FlexPagerAdapter()  adapter.addItems(
  TextItem("Look at these pictures"),
  PictureItem(R.drawable.picture_1),
  PictureItem(R.drawable.picture_2) )  view_pager.adapter = adapter

That's all that's required to implement multiple layouts in a ViewPager. No need to create Fragments or manage lifecycles. The same classes can be used in both the FlexAdapter and FlexPagerAdapter. The span, dragDirs, and swipeDirs values will just be ignored on items added to a FlexPagerAdapter.

You can see a sample that uses the FlexPagerAdapter here.

Download

FlexAdapter is distributed with JitPack

repositories {

  maven {
 url "https://jitpack.io" 
}
 
}
  dependencies {

 compile 'com.github.ajalt:flexadapter:2.1.0' 
}

License

Copyright 2016 AJ Alt  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

Basic implementation of Android Recycler View purely written in Kotlin.

The ultimate developer guide to Android application linking methods.

Android library that makes it easy to create floating UI elements.

RIBs is the cross-platform architecture framework behind many mobile apps at Uber. The name RIBs is short of Router, Interactor and Builder, which are core components of this architecture. This framework is designed for mobile apps with a large number of engineers and nested states.

A collection of quickstart samples demonstrating the Firebase APIs on Android.

stringX SDK is a single integrated platform delivering automated translation of your app to over 100 languages. It works from the user perspective the same way as web pages on chrome. User can choose whether to use translated version of the app or one with default locale.

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