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

RecyclerView Animators is an Android library that allows developers to easily create RecyclerView with animations.

Read incoming and outgoing text messages using an Android application across different Android SDK versions it's not trivial. If yo don't want to appear as SMS application and your application has to read incoming and outgoing SMSs this is your library.

This Android library offers you two main classes to use to start listening text messages. SMS Radar is implemented in top of an Android service. To start / stop listening text messages use SmsRadar.initializeSmsRadarService(context, listener) with a Context instance and a SmsListener implementation.

Fast JSON Processor.

android-asyncservice manages threading and caching transparently in your Android app.

It's an alternative to AsyncTasks, Loaders, or more advanced libs like RxJava, Robospice, Groundy, … but AsyncService focuses on keeping your code short and simple!

BaseAdapterHelper aims to make BaseAdapter's getView() method much more readable, getting rid of the ViewHolder pattern boilerplate code.

QuickAdapter allows you to shorten the code of most usual BaseAdapter, taking care of implementing everything for you based on your data list. You only need to focus on the mapping between your view and your model.

Android PDFView is a library which provides a fast PDFView component for Android, with animations, gestures, and zoom. It's based on VuDroid for decoding the PDF file.

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