Renderers


Source link: https://github.com/pedrovgs/Renderers

Renderers

Renderers is an Android library created to avoid all the RecyclerView/Adapter boilerplate needed to create a list of data in your app and all the spaghetti code that developers used to create following the ViewHolder classic implementation. As performance is also important for us, we've added a new diffUpdate method supporting differential updated transparently.

With this library you can improve your RecyclerView/Adapter/ViewHolder code. The one sometimes we copy and paste again and again 😃. Using this library you won't need to create any new class extending from RecyclerViewAdapter.

Create your Renderer classes and declare the mapping between the object to render and the Renderer. The Renderer will use the model information to draw your user interface. You can reuse them in all your RecyclerView and ListView implementations easily. That's it!

Screenshots

Usage

To use Renderers Android library you only have to follow three steps:

    1. Create your Renderer class or classes extending Renderer<T>. Inside your Renderer classes. You will have to implement some methods to inflate the layout you want to render and implement the rendering algorithm.
public class VideoRenderer extends Renderer<Video> {

@BindView(R.id.iv_thumbnail)

  ImageView thumbnail;

  @BindView(R.id.tv_title)

  TextView title;

  @BindView(R.id.iv_marker)

  ImageView marker;

  @BindView(R.id.tv_label)

  TextView label;

@Override

  protected View inflate(LayoutInflater inflater, ViewGroup parent) {

View inflatedView = inflater.inflate(R.layout.video_renderer, parent, false);

ButterKnife.bind(this, inflatedView);

return inflatedView;

  
}

@Override

  protected void render() {

Video video = getContent();

renderThumbnail(video);

renderTitle(video);

renderMarker(video);

renderLabel();

  
}

@OnClick(R.id.iv_thumbnail)

  void onVideoClicked() {

Video video = getContent();

Log.d("Renderer", "Clicked: " + video.getTitle());

  
}

private void renderThumbnail(Video video) {

Picasso.with(context).load(video.getResourceThumbnail()).placeholder(R.drawable.placeholder).into(thumbnail);

  
}

private void renderTitle(Video video) {

this.title.setText(video.getTitle());

  
}
 
}

You can use Jake Wharton's Butterknife library to avoid findViewById calls inside your Renderers if you want. But the usage of third party libraries is not mandatory.

    1. If you have just one type of item in your list, instantiate a RendererBuilder with a Renderer instance and you are ready to go:
Renderer<Video> renderer = new LikeVideoRenderer();
 RendererBuilder<Video> rendererBuilder = new RendererBuilder<Video>(renderer);

If you need to render different objects into your list you can use RendererBuilder.bind fluent API and that's it:

RendererBuilder<Video> rendererBuilder = new RendererBuilder<Video>()

 .bind(VideoHeader.class, new VideoHeaderRenderer())

 .bind(Video.class, new LikeVideoRenderer());
    1. Initialize your ListView or RecyclerView with your RendererBuilder and your AdapteeCollection instances inside your Activity or Fragment. You can use ListAdapteeCollection or create your own implementation creating a class which implements AdapteeCollection to configure your RendererAdapter or RVRendererAdapter.
private void initListView() {

  adapter = new RendererAdapter<Video>(rendererBuilder, adapteeCollection);

  listView.setAdapter(adapter);
 
}

or

private void initListView() {

  adapter = new RVRendererAdapter<Video>(rendererBuilder, adapteeCollection);

  recyclerView.setAdapter(adapter);
 
}

Remember, if you are going to use RecyclerView instead of ListView you'll have to use RVRendererAdapter instead of RendererAdapter.

    1. Diff updates:

If the RecyclerView performance is crucial in your application remember you can use diffUpdate method in your RVRendererAdapter instance to update just the items changed in your adapter and not the whole list.*

adapter.diffUpdate(newList)

This method provides a ready to use diff update for our adapter based on the implementation of the standard equals and hashCode methods from the Object Java class. The classes associated to your renderers will have to implement equals and hashCode methods properly. Your hashCode implementation can be based on the item ID if you have one. You can use your hashCode implementation as an identifier of the object you want to represent graphically. We know this implementation is not perfect, but is the best we can do wihtout adding a new interface you have to implement to the library breaking all your existing code. Here you can review the DiffUtil.Callback implementation used in this library. If you can't follow this implementation you can always use a different approach combined with your already implemented renderers.

Usage

Add this dependency to your build.gradle:

dependencies{

  compile 'com.github.pedrovgs:renderers:3.3.3' 
}

Complex binding

If your renderers binding is complex and it's not based on different classes but in properties of these classes, you can also extend RendererBuilder and override getPrototypeClass to customize your binding as follows:

public class VideoRendererBuilder extends RendererBuilder<Video> {

 public VideoRendererBuilder() {

  List<Renderer<Video>> prototypes = getVideoRendererPrototypes();

  setPrototypes(prototypes);

}

 /** 
* Method to declare Video-VideoRenderer mapping. 
* Favorite videos will be rendered using FavoriteVideoRenderer. 
* Live videos will be rendered using LiveVideoRenderer. 
* Liked videos will be rendered using LikeVideoRenderer. 
* 
* @param content used to map object-renderers. 
* @return VideoRenderer subtype class. 
*/
@Override
protected Class getPrototypeClass(Video content) {

  Class prototypeClass;
  if (content.isFavorite()) {

 prototypeClass = FavoriteVideoRenderer.class;
  
}
 else if (content.isLive()) {

 prototypeClass = LiveVideoRenderer.class;
  
}
 else {

 prototypeClass = LikeVideoRenderer.class;
  
}

  return prototypeClass;

}

 /** 
* Create a list of prototypes to configure RendererBuilder. 
* The list of Renderer<Video> that contains all the possible renderers that our RendererBuilder 
* is going to use. 
* 
* @return Renderer<Video> prototypes for RendererBuilder. 
*/
private List<Renderer<Video>> getVideoRendererPrototypes() {

  List<Renderer<Video>> prototypes = new LinkedList<Renderer<Video>>();

  LikeVideoRenderer likeVideoRenderer = new LikeVideoRenderer();

  prototypes.add(likeVideoRenderer);

FavoriteVideoRenderer favoriteVideoRenderer = new FavoriteVideoRenderer();

  prototypes.add(favoriteVideoRenderer);

LiveVideoRenderer liveVideoRenderer = new LiveVideoRenderer();

  prototypes.add(liveVideoRenderer);

return prototypes;

}
 
}

References

You can find implementation details in these talks:

Software Design Patterns on Android Video

Software Design Patterns on Android Slides

Developed By

License

Copyright 2016 Pedro Vicente Gómez Sánchez  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

Multi Line Radio Group is a Radio Group layout to show radio buttons in more than one line.

Riffsy RecyclerView MVP Grid Example using Dagger 2, Retrofit 2, RxJava 2 and Butterknife with Junit and Espresso tests.

This library allows to use hamburger to arrow animation for navigation in app.

A general purpose android UI library to show a user show menu in accordance of Floating action button with modern way of material design guidelines.

A showcase of RxJava and Model View Presenter, plus a number of other popular libraries for android development, including AutoValue, Retrofit, Moshi, and ButterKnife. Unit tests covering any business logic and Robolectric tests verifying the ui.

Converts a string to a slug.

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