DataBinding for RecyclerView


Source link: https://github.com/drstranges/DataBinding_For_RecyclerView

DataBinding for RecyclerView

Overview

This library provides simple and flexible way to configuration RecyclerView using android data binding.

Add library as gradle dependency

 repositories {

jcenter()
  
}

  dependencies {

compile 'com.drextended.rvdatabinding:rvdatabinding:1.1.0'
  
}

// Don't forget to enable data binding
  dataBinding {

enabled = true
  
}

Features

  • .ListConfig - Simple builder for configuration RecyclerView.
  • .BindableAdapter - Simple Recycler View Adapter for using with data-binding.
  • .BindingHolder - Simple View Holder for using with data-binding.
  • .DividerItemDecoration - Simple divider decoration for RecyclerView.
  • .ColorDividerItemDecoration - Simple colored divider decoration for RecyclerView.
  • .LoadMoreScrollListener - Simple RecyclerView ScrollListener for implementing lazy loading list (endless list).
  • .TwoWayLoadingScrollListener - Simple RecyclerView ScrollListener for implementing two-way lazy loading list (endless list).
  • .BaseBindingAdapterDelegate - Base RecyclerView item delegate for using with data-binding.
  • .ModelItemDelegate - Generic ActionDelegate. You can use this one if you do not want to implement custom one.

Usage

###1. At first you definitely should have pojo-models for items

 public class User implements BaseModel {

public String name;

public String avatar;
  
}

  public class Location implements BaseModel {

public String name;

public String image;
  
}

  public class Advertisement implements BaseModel {

public String label;

public String image;
  
}

###2. Then you should create layouts for each item and for your list page

fragment_page.xml

 <layout ...>

<data>

 <variable

  name="viewModel"

  type="com.drextended.rvdbsample.viewmodel.ListViewModel"/>

</data>

 <android.support.v7.widget.RecyclerView

 android:layout_width="match_parent"

 android:layout_height="match_parent"

 app:listConfig="@{
viewModel.getListConfig()
}
"/>

</layout>

item_user.xml

 <layout xmlns:...>

<data>

 <import type="com.drextended.rvdbsample.model.ActionType"/>

  <variable

  name="user"

  type="com.drextended.rvdbsample.model.User"/>

  <variable

  name="actionHandler"

  type="com.drextended.actionhandler.listener.ActionClickListener"/>

</data>

 <android.support.v7.widget.CardView

 ...

 app:actionHandler="@{
actionHandler
}
"

 app:actionType="@{
ActionType.OPEN
}
"

 app:actionTypeLongClick="@{
ActionType.MENU
}
"

 app:model="@{
user
}
">

  <FrameLayout ...>

<ImageView

...

app:glideAnimation="@{
R.anim.scale_in
}
"

app:glideCacheStrategy='@{
"RESULT"
}
'

app:glidePath="@{
user.avatar
}
"

app:glidePlaceholder="@{
@android:drawable/ic_menu_gallery
}
"

app:glideTransform='@{
"CIRCLE"
}
'

tools:src="@android:drawable/ic_menu_gallery"/>

<TextView

...

android:text="@{
user.name
}
"/>

  </FrameLayout>

</android.support.v7.widget.CardView>
  </layout>

The same for item_location.xml and for item_advertisement.xml

###3. Then create ItemDelegates for items if you do not want to use generic

UserDelegate.java

 public class UserDelegate extends ActionAdapterDelegate<BaseModel, ItemUserBinding> {

 public UserDelegate(final ActionClickListener actionHandler) {

 super(actionHandler);

}

 @Override

public boolean isForViewType(@NonNull final List<BaseModel> items, final int position) {

 return items.get(position) instanceof User;

}

 @NonNull

@Override

public BindingHolder<ItemUserBinding> onCreateViewHolder(final ViewGroup parent) {

 return BindingHolder.newInstance(R.layout.item_user, LayoutInflater.from(parent.getContext()), parent, false);

}

 @Override

public void onBindViewHolder(@NonNull final List<BaseModel> items, final int position, @NonNull final BindingHolder<ItemUserBinding> holder) {

 final User user = (User) items.get(position);

 holder.getBinding().setUser(user);

 holder.getBinding().setActionHandler(getActionHandler());

}

 @Override

public long getItemId(final List<BaseModel> items, final int position) {

 return items.get(position).getId();

}

  
}

###4. Assemble all this in your viewmodel

AllInOneListViewModel.java

 // Used action-handler library for handling click/long click in items: https://github.com/drstranges/ActionHandler
  final ActionClickListener actionHandler = new ActionHandler.Builder()

 //.addAction(null, new SimpleAnimationAction()) // Applied for any actionType

 //.addAction(null, new TrackAction()) // Applied for any actionType

 .addAction(ActionType.OPEN, new OpenProfileAction())

 .addAction(ActionType.MENU, new CompositeAction<String>(

(context, model) -> getTitle(model),

new ActionItem(ActionType.MENU_ITEM_1, new OpenSecondActivity(), R.string.menu_item_1),

new ActionItem(ActionType.MENU_ITEM_2, new ShowToastAction(), R.string.menu_item_2)

))

 .setActionInterceptor(this)

 .setActionFiredListener(this)

 .build();

// Build generic bindable adapter. Just list all used item delegates
  mAdapter = new BindableAdapter<>(

 new UserDelegate(actionHandler), // you can create custom delegate

 //new ModelActionItemDelegate<BaseModel>(actionHandler, User.class, R.layout.item_user, BR.user), // or use generic

 new ModelActionItemDelegate<BaseModel>(actionHandler, Location.class, R.layout.item_location, BR.location),

 new ModelActionItemDelegate<BaseModel>(actionHandler, Advertisement.class, R.layout.item_advertisment, BR.advertisment)
  );

// Config for RecyclerView
  mListConfig = new ListConfig.Builder(mAdapter)

 .setLayoutManagerProvider(new SimpleGridLayoutManagerProvider(mSpanCount, getSpanSizeLookup())) // if not set, LinearLayoutManager applied by default

 .addItemDecoration(new ColorDividerItemDecoration(color, spacing, SPACE_LEFT|SPACE_TOP, false))

 //.setDefaultDividerEnabled(true)

 .addOnScrollListener(new OnLoadMoreScrollListener(mCallback))

 .setItemAnimator(getCustomItemAnimator()) //

.setHasFixedSize(true)

 .setItemTouchHelper(getItemTouchHelper())

 .build(context);

loadData();

Used Library:

Inspired by:

https://github.com/sockeqwe/AdapterDelegates

http://hannesdorfmann.com/android/adapter-delegates

Sample

Sample apk file

License

Copyright 2016 Roman Donchenko  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

Rapidly fast implementation of SharedPreferences which stores each preference in files separately, performs disk IO via NIO with memory mapped byte buffers and works IPC (between processes).

This library introduces dynamic control over vector drawables. Each and every aspect of a vector drawable can be controlled dynamically (via Java instances), using this library.

Features :

  • Control : Control every attribute related to path, group, vector and clip-path like color, alpha, strokeWdith, translation, scale, rotation etc.
  • Clip Paths : The library supports clip paths.
  • Trimming : The library allows trimming of path by using trimEnd, trimStart and trimOffset parameters.

A simple tree view with drag and drop capabilities.

A sample application showы how to realize immersive parallax effect header like Google Play app.

A custom GLSurfaceView to show image with ripple effect using OpenGL.

A powerful, flexible and easy to use Video and Image compression library for Android.

Image

It's usually said that "A picture is worth a thousand words". Images adds flair and beauty to our android apps, but we usaully have problems with these images due to thier large size. With SiliCompressor you can now compress and use your images more smoothly.

Video

Due to the high resolution of our Smartphone cameras and cameras from other devices, Video files have become large in size and thus difficult for it to be shared with others on social apps, social media and even when we need to upload it on our server. With SiliCompressor you can now compress your video file while maintaining it quality.

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