Groupie


Source link: https://github.com/Genius/groupie

groupie

Groupie is a simple, flexible library for complex RecyclerView layouts.

Groupie lets you treat your content as logical groups and handles change notifications for you -- think sections with headers and footers, expandable groups, blocks of vertical columns, and much more. It makes it easy to handle asynchronous content updates and insertions and user-driven content changes. At the item level, it abstracts the boilerplate of item view types, item layouts, viewholders, and span sizes.

Try it out:

Groupie plays best with Kotlin and Kotlin Android extensions. Never write a ViewHolder again—Kotlin generates view references and Groupie uses a generic holder. Setup here.

You can also use Groupie with Java and your existing ViewHolders.

compile 'com.xwray:groupie:2.0.0-alpha2'

Groupie also supports Android's data binding to generate view holders. Setup here.

compile 'com.xwray:groupie-databinding:2.0.0-alpha2' 

The last stable release ONLY supported data binding. It was:

compile 'com.xwray:groupie:1.1.1'

Which one to choose? It's up to you and what your project already uses. You can even use Kotlin and data binding together. * Or all your existing hand-written Java ViewHolders, and one new Kotlin item to try it out. Go crazy!

Get started

Use a GroupAdapter anywhere you would normally use a RecyclerView.Adapter, and attach it to your RecyclerView as usual.

GroupAdapter adapter = new GroupAdapter();
 recyclerView.setAdapter(adapter);

Groups

Groups are the building block of Groupie. An individual Item (the unit which an adapter inflates and recycles) is a Group of 1. You can add Groups and Items interchangeably to the adapter.

groupAdapter.add(new HeaderItem());
 groupAdapter.add(new CommentItem());
  Section section = new Section();
 section.setHeader(new HeaderItem());
 section.addAll(bodyItems);
 groupAdapter.add(section);

Modifying the contents of the GroupAdapter in any way automatically sends change notifications. Adding an item calls notifyItemAdded(); adding a group calls notifyItemRangeAdded(), etc.

Modifying the contents of a Group automatically notifies its parent. When notifications reach the GroupAdapter, it dispatches final change notifications. There's never a need to manually notify or keep track of indices, no matter how you structure your data.

section.removeHeader();
 // results in a remove event for 1 item in the adapter, at position 2

There are a few simple implementations of Groups within the library:

  • Section, a list of body content with an optional header group and footer group.
  • ExpandableGroup, a single parent group with a list of body content that can be toggled hidden or shown.
  • UpdatingGroup, a list of items which can diff its previous and new contents and animate moves, updates and other changes

Groups are flexible and composable. They can be combined and nested to arbitrary depth. For example, you could make an UpdatingSection by adding a single UpdatingGroup to the content of a Section.

public class UpdatingSection extends Section {

  private final UpdatingGroup updatingGroup;

public UpdatingSection() {

setHeader(new HeaderItem("Updating section!");

updatingGroup = new UpdatingGroup();

  
}

public void update(List<Item> list) {

updatingGroup.update(list);

  
}
 
}

Life is messy, so groups are designed so that making new ones and defining their behavior is easy. You should make many small, simple, custom groups as the need strikes you.

You can implement the Group interface directly if you want. However, in most cases, you should extend the base implementation, NestedGroup. NestedGroup provides support for arbitrary nesting of groups, registering/unregistering listeners, and fine-grained change notifications to support animations and updating the adapter.

Items

Groupie abstracts away the complexity of multiple item view types. Each Item declares a view layout id, and gets a callback to bind the inflated layout. That's all you need; you can add your new item directly to a GroupAdapter and call it a day.

Item with Kotlin:

The Item class gives you simple callbacks to bind your model object to the generated fields. Because of Kotlin Android extensions, there's no need to write a view holder.

import kotlinx.android.synthetic.main.song.view.*  class SongItem constructor(private val song: Song) : Item<ViewHolder>() {

override fun getLayout() = R.layout.song

override fun bind(viewHolder: ViewHolder, position: Int) {

viewHolder.itemView.title.text = song.title

viewHolder.itemView.title.artist = song.artist
  
}
 
}

If you're converting existing ViewHolders, you can leave them as they are by making an Item<MyViewHolder>.

Item with data binding:

The Item class gives you simple callbacks to bind your model object to the generated binding. Because of data binding, there's no need to write a view holder.

public class SongItem extends BindableItem<SongBinding> {

public SongItem(Song song) {

this(song);

  
}

 @Override public void bind(SongBinding binding, int position) {

binding.setSong(song);

  
}

@Override public int getLayout() {

return R.layout.song;
  
}
 
}

If you're converting existing ViewHolders, you can reference any named views (e.g. R.id.title) directly from the binding instead.

 @Override public void bind(SongBinding binding, int position) {

binding.title.setText(song.getTitle());

  
}

You can also mix and match BindableItem and other Items in the adapter, so you can leave legacy viewholders as they are by making an Item<MyExistingViewHolder>.

Note:

Items can also declare their own column span and whether they are draggable or swipeable.

Gradle setup

Kotlin

In your app build.gradle file, include:

apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions'  buildscript {

  ext.kotlin_version = '1.1.1'
  repositories {

jcenter()
  
}

  dependencies {

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
  
}
 
}
  dependencies {

  compile 'com.xwray:groupie:2.0.0-alpha2'
  compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" 
}

Remember to include

import kotlinx.android.synthetic.main.my_item_layout.view.*

in the corresponding Item class for generated view references.

Data binding

Add to your app module's build.gradle:

android {

  dataBinding {

enabled = true
  
}
 
}
  dependencies {

  compile 'com.xwray:groupie-databinding:2.0.0-alpha2' 
}

Then, just wrap each item layout in <layout> tags. (The <data> section is optional.)

layout/item_song.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools">
  <data>

<variable name="song" type="com.example.Song" />
  </data>

<FrameLayout

 android:layout_width="match_parent"

android:layout_height="wrap_content" >

 <TextView

 android:id="@+id/title"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_gravity="center"

 android:text="@{
song.title
}
"

 tools:text="A Song Title" />

</FrameLayout> </layout>

Bindings are only generated for layouts wrapped with tags, so there's no need to convert the rest of your project (unless you want to).

You can add a <data> section to directly bind a model or ViewModel, but you don't have to. The generated view bindings alone are a huge time saver.

Kotlin AND data binding?

Sure, why not? Follow all the instructions from both sections above. You only need to include the groupie-databinding dependency, and omit the references to android-extensions. You'll make BindableItems instead of importing and using Kotlin extensions.

Contributing

Contributions you say? Yes please!

Bug report?

  • If at all possible, please attach a minimal sample project or code which reproduces the bug.
  • Screenshots are also a huge help if the problem is visual.

Send a pull request!

  • If you're fixing a bug, please add a failing test or code that can reproduce the issue.

Notes

Pre-release versions of groupie had a different package name. The last working build was:

compile 'com.genius:groupie:0.7.0'

If you try it out, I'd love to know what you think. Please hit up Lisa at [first][last]@gmail.com or on Twitter at @lisawrayz.

Resources

This is an encryption example of RSA and AES (CBC, ECB, CTR) 256 bit key on android with unit tests.

AndroidStudio/IntelliJ IDEA code style settings for Android projects.

A nearby handling APIs for Android Apps using RxJava.

An android app to track bus status of Zhuhai using RxJava and Android Data Binding library.

A Kotlin extensions for Android.

Android Login and register template with different backends.

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