ViewCellAdapter


Source link: https://github.com/gantonious/ViewCellAdapter

ViewCellAdapter

A RecyclerView adapter that can handle holding hetrogeneuous data types, and provides the ability to set up sections in your adapter. View the sample-app to see different usage scenarios.

Features

Creating a ViewCell

When you want to bind an item to a ViewCellAdapter you need a model to bind, a layout to bind to, and a ViewCell to handle the binding logic.

Define a Model

public class Task {

  public final String name;
  public final int timesCompleted;

public Task(String name, int numCompletions) {

this.name = name;

this.timesCompleted = numCompletions;
  
}
 
}

Define a Layout

<?xml version="1.0" encoding="utf-8"?> <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="8dp">

<TextView

android:id="@+id/task_title"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

<TextView

android:id="@+id/task_num_completions"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="8dp"/>  </LinearLayout>

Define a ViewCell

public class TaskViewCell extends GenericViewCell<TaskViewCell.TaskViewHolder, Task> {

public TaskViewCell(Task model) {

super(model);

  
}

@Override
  public int getLayoutId() {

return R.layout.task_list_item;
  
}

@Override
  public void bindViewCell(TaskViewHolder viewHolder) {

Task task = getModel();

 viewHolder.setTaskName(task.name);

viewHolder.setNumberOfCompletions(task.timesCompleted);

  
}

public static class TaskViewHolder extends BaseViewHolder {

private TextView taskNameTextView;

private TextView numberOfCompletionsTextView;

 public ViewHolder(View itemView) {

 super(itemView);

  taskNameTextView = (TextView) itemView.findViewById(R.id.task_title);

 numberOfCompletionsTextView = (TextView) itemView.findViewById(R.id.task_num_completions);

}

 public void setTaskName(String taskName) {

 taskNameTextView.setText(taskName);

}

 public void setNumberOfCompletions(int numCompletions) {

 String numberOfCompletions = String.valueOf(numCompletions);

 numberOfCompletionsTextView.setText(numberOfCompletions);

}

  
}
 
}

Using the Adapter

The ViewCellAdapter takes in a list of sections. You can then update each section independently to change what is being rendered.

Using a HomogeneousSection

The simplest way to get started is to use a HomogeneousSection. A HomogeneousSection assumes all view cells in the section are binding the same data type.

HomogeneousSection<Task, TaskViewCell> todaysTasksSection = new HomogeneousSection<>(Task.class, TaskViewCell.class);
 HomogeneousSection<Task, TaskViewCell> olderTasksSection = new HomogeneousSection<>(Task.class, TaskViewCell.class);
  ViewCellAdapter viewCellAdapter = new ViewCellAdapter();
 viewCellAdapter.addSection(todaysTasksSection);
 viewCellAdapter.addSection(olderTasksSection);
  recyclerView.setAdapter(viewCellAdapter);

Then each section can be updated independently

List<Task> todaysTasks = getTodaysTasks();
 todaysTasksSection.addAll(todaysTasks);
  List<Task> olderTasks = getOlderTasks();
 olderTasksSection.addAll(olderTasks);

Using a Section

A Section does not assume all of it's viewcells are the same type. This allows it to be populated with different view cells that don't share the same view type.

Section heterogeneousSection = new Section();
  ViewCellAdapter viewCellAdapter = new ViewCellAdapter();
 viewCellAdapter.addSection(heterogeneousSection);
  recyclerView.setAdapter(viewCellAdapter);

A Section can be populated by doing the following (notice the extra level of indirection required to convert the models into viewcells)

Task importantTask = new Task("Important Task", 0);
 Task normalTask = new Task("Normal Task", 0);
  heterogeneousSection.add(new ImportantTaskViewCell(importantTask));
 heterogeneousSection.add(new TaskViewCell(normalTask));

Decorating Sections

It's common to want to add a header or a footer to a list of items. Rather than manually inserting a viewcell at the beginning or end of a section, a SectionDecorator can be used to decorate a section with a header or footer.

HomogeneousSection<Task, TaskViewCell> todaysTasksSection = new HomogeneousSection<>(Task.class, TaskViewCell.class);
  HeaderSectionDecorator todaysTasksWithHeader = new HeaderSectionDecorator(todaysTasksSection, new HeaderViewCell("Today's Tasks"));
 todaysTasksWithHeader.setShowHeaderIfEmpty(false);
  ViewCellAdapter viewCellAdapter = new ViewCellAdapter();
 viewCellAdapter.addSection(todaysTasksWithHeader);
  recyclerView.setAdapter(viewCellAdapter);

Since a SectionDecorator is a section, you can decorate a decorator to construct complex list setups with ease. The following example applies a header and an empty view to a single section.

HomogeneousSection<Task, TaskViewCell> todaysTasksSection = new HomogeneousSection<>(Task.class, TaskViewCell.class);
  HeaderSectionDecorator todaysTasksWithHeader = new HeaderSectionDecorator(todaysTasksSection, new HeaderViewCell("Today's Tasks"));
 todaysTasksWithHeader.setShowHeaderIfEmpty(false);
  EmptySectionDecorator todaysTasksWithHeaderAndEmptyView = new EmptySectionDecorator(todaysTasksWithHeader, new EmptyViewCell("You have no tasks to do today!"));
  ViewCellAdapter viewCellAdapter = new ViewCellAdapter();
 viewCellAdapter.addSection(todaysTasksWithHeaderAndEmptyView);
  recyclerView.setAdapter(viewCellAdapter);

Using Section Builders

When you need to build a more complex adapter, SectionBuilder provides a clean declarative API to build your adapter. The following example shows how to build the same setup described in the last example using the SectionBuilder API.

HomogeneousSection<Task, TaskViewCell> todaysTasksSection = new HomogeneousSection<>(Task.class, TaskViewCell.class);
  ViewCellAdapter adapter = ViewCellAdapter.create()
  .section(

SectionBuilder.wrap(todaysTasksSection)

 .header(new HeaderViewCell("Today's Tasks"))

 .hideHeaderIfEmpty()

 .showIfEmpty(new EmptyViewCell("You have no tasks to do today!"))
  )
  .build();

Using your old adapters

If you have a legacy adapter that is not easy to convert to this library's API you can wrap it in an AdapterWrapperSection. This allows you to insert your old adapter as a section in a ViewCellAdapter. It also lets you decorate it using any SectionDecorator.

RecyclerView.Adapter legacyTasksAdapter = ...; AbstractSection tasksSection = new AdapterWrapperSection<>(legacyTasksAdapter);
  // integrate this section with the ViewCellAdapter API

Handling ViewHolder Events

Often times an event can occur in a view holder that you may want to handle in the parent activity/fragment. This can be done by using the @BindListener annotation in the viewcell.

Step 1: Define an event handler interface

public interface OnTaskClickListener {

  void onTaskClicked(Task task);
 
}

Step 2: Bind the interface to the view holder inside the ViewCell

@BindListener public void bindOnTaskClick(TaskViewHolder viewHolder, OnTaskClickListener onTaskClickListener) {

  viewHolder.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

 onTaskClickListener.onTaskClicked(getModel());

}

  
}
);
 
}

Step 3: Handle event in activity/fragment

viewCellAdapter.addListener(new TaskViewCell.OnTaskClickListener() {

  @Override
  public void onTaskClicked(Task task) {

// handle event
  
}
 
}
);

Download

dependencies {

  compile 'ca.antonious:viewcelladapter:2.4.0'
  annotationProcessor 'ca.antonious:viewcelladapter-compiler:2.4.0' 
}

License

MIT License  Copyright (c) 2016 George Antonious  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

Resources

With this SDK you can access the API behind the DRAE (Diccionario de la Real Academia Española, the official spanish dictionary) in order to use it in your own app.

Shortify is used for minimizing your coding effort in your development environment. It has some builtin method and classes which helps you in creating mostly used element and tasks in Android app.

Android library handling flashlight for camera and camera2 api. Added support for handling display/screen light.

Yet Another Android animated Seekbar inspired from Philips Hue app.

Great sound quality, audio cleanliness and very smooth interface. Playing the folder structure, artist or album or create your own playlists with local or online tracks.

  • 10-band equalizer
  • Themes
  • mp3, flac, aac, ogg, oga, m4a, m4b, m4p, wma and other audio formats

Shape Ripple is a library that emulates a ripple like animations with cool tweaks on the go. It runs on API level 11 and upwards.

As addition you can even create your own shape renderer through the canvas to create a custom shape ripple.

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