OneAdapter

Additional

Language
Kotlin
Version
N/A
Created
Nov 21, 2018
Updated
Nov 28, 2019
Owner
ironSource
Contributor
idanatz
1
Activity
Badge
Generate
Download
Source code

Commercial

OneAdapter

OneAdapter is made to simplify and enhance the use of the RecyclerView's Adapter while preventing common mistakes. With multiple modules and hooks, you don't have to think about writing an adapter anymore, and just focus on what matters.

For better understanding what drove me to write this library and what use cases it solves best, please refer to my Medium post: https://medium.com/@idanatsmon/adapting-your-recyclerview-the-2019-approach-e47edf2fc4f3

Features:

Include in your project

dependencies {
  implementation "com.ironsource.aura.oneadapter:oneadapter:${LATEST_VERSION}"
}

Note that library interfaces and API may change slightly while the library design matures. Please see the changes in the CHANGELOG file before upgrading.

Preview

Example

You can try out the example project that includes basic and advanced usage both in Java and Kotlin.

Screenshots



Basic Usage

1. Implement Item Module

Item Modules are used for the creation and binding of all ViewHolders for you. In the onBind method, you will receive as a parameter the model associated with this view and a ViewBinder class that lets you find (and cache) the views defined in the associated layout file.

Java
class MessageModule extends ItemModule<MessageModel> {
      @NotNull @Override
      public ItemModuleConfig provideModuleConfig() {
          return new ItemModuleConfig() {
              @Override
              public int withLayoutResource() { return R.layout.message_model; }
          };
      }

      @Override
      public void onBind(@NotNull MessageModel model, @NotNull ViewBinder viewBinder) {
          TextView title = viewBinder.findViewById(R.id.title);
          title.setText(model.title);
      }
    
     @Override
      public void onUnbind(@NotNull ViewBinder viewBinder) {
          // unbind logic like stop animation, release webview resources, etc.
      }
}
Kotlin
class MessageModule : ItemModule<MessageModel>() {
    override fun provideModuleConfig() = object : ItemModuleConfig() {
        override fun withLayoutResource() = R.layout.message_model
    }

    override fun onBind(model: MessageModel, viewBinder: ViewBinder) {
        val title = viewBinder.findViewById<TextView>(R.id.title)
        title.text = model.title
    }

    override fun onUnbind(viewBinder: ViewBinder) {
        // unbind logic like stop animation, release webview resources, etc.
    }
}

2. Implement Diffable

The Adapter is calculating the difference between its current data and the modified data on a background thread and posting the result to the main thread. In order for this magic to work without writing tons of DiffUtil.Callback, your models need to implement one simple interface:

Java
public class MessageModel implements Diffable {
    private int id;
    private String title;

    @Override
    public long getUniqueIdentifier() {
        return id;
    }

    @Override
    public boolean areContentTheSame(@NotNull Object other) {
        return other instanceof MessageModel && title.equals(((MessageModel) other).title);
    }
}
Kotlin
class MessageModel : Diffable {
    private val id: Int = 0
    private val title: String? = null

    override fun getUniqueIdentifier(): Long = id.toLong()
    override fun areContentTheSame(other: Any): Boolean = other is MessageModel && title == other.title
}

3. Attach To OneAdapter & Use

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachItemModule(new MessageModule());
    
oneAdapter.setItems(...)  
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachItemModule(MessageModule());
    
oneAdapter.setItems(...) 



Advanced Usage

Modules

Multiple Types

Have more than one view type? not a problem, just create another ItemModule and attach it to OneAdapter in the same way.

1. Implement Multiple Item Modules

class MessageModule extends ItemModule<MessageModel> { ... }
class StoryModule extends ItemModule<StoryModel> { ... }

2. Attach To OneAdapter

OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachItemModule(new MessageModule())
    .attachItemModule(new StoryModule())
    ...



Paging Module

Paging Module is used for creating and binding a specific ViewHolder at the end of the list when the Adapter reaches a load more state. The visible threshold configuration is used to indicate how many items before the end of the list the onLoadMore callback should be invoked.

1. Implement Paging Modules

Java
class PagingModuleImpl extends PagingModule {
    @NotNull @Override
    public PagingModuleConfig provideModuleConfig() {
        return new PagingModuleConfig() {
            @Override
            public int withLayoutResource() { return R.layout.load_more; } // can be some loading animation.

            @Override
            public int withVisibleThreshold() { return 3; } // invoke onLoadMore 3 items before the end.
        };
    }

    @Override
    public void onLoadMore(int currentPage) {
        // place your load more logic here, like asking the ViewModel to load the next page of data.
    }
}
Kotlin
class PagingModuleImpl : PagingModule() {
    override fun provideModuleConfig() = object : PagingModuleConfig() {
        override fun withLayoutResource() = R.layout.load_more // can be some spinner animation
        override fun withVisibleThreshold() = 3 // invoke onLoadMore 3 items before the end
    }

    override fun onLoadMore(currentPage: Int) {
        // place your load more logic here, like asking the ViewModel to load the next page of data.
    }
}

2. Attach To OneAdapter

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachPagingModule(new PagingModuleImpl())
    ...
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachPagingModule(PagingModuleImpl())
    ...



Emptiness Module

Emptiness Module is used for creating and binding a specific ViewHolder when the Adapter has no data to render.

1. Implement Emptiness Modules

Java
class EmptinessModuleImpl extends EmptinessModule {
    @NotNull @Override
    public EmptinessModuleConfig provideModuleConfig() {
        return new EmptinessModuleConfig() {
            @Override
            public int withLayoutResource() { return R.layout.empty_state; }
        };
    }

    @Override
    public void onBind(@NotNull ViewBinder viewBinder) { ... }

    @Override
    public void onUnbind(@NotNull ViewBinder viewBinder) { ... }
}
Kotlin
class EmptinessModuleImpl : EmptinessModule() {
    override fun provideModuleConfig(): EmptinessModuleConfig = object : EmptinessModuleConfig() {
        override fun withLayoutResource() = R.layout.empty_state
    }

    override fun onBind(viewBinder: ViewBinder) { ... }

    override fun onUnbind(viewBinder: ViewBinder) { ... }
}

2. Attach To OneAdapter

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachEmptinessModule(new EmptinessModuleImpl())
    ...
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachEmptinessModule(EmptinessModuleImpl())
    ...



Selection Module

Selection Module is used for enabling single or multiple selection on Items.

1. Implement Selection Modules

Java
class ItemSelectionModuleImpl extends ItemSelectionModule {
    @NotNull @Override
    public ItemSelectionModuleConfig provideModuleConfig() {
        return new ItemSelectionModuleConfig() {
            @NotNull @Override
            public SelectionType withSelectionType() { return SelectionType.Multiple; } // Or SelectionType.Single.
        };
    }

    @Override
    public void onSelectionUpdated(int selectedCount) {
       // place your general selection logic here, like changing the toolbar text to indicate the selected count.
    }
}
Kotlin
class ItemSelectionModuleImpl : ItemSelectionModule() {
    override fun provideModuleConfig(): ItemSelectionModuleConfig = object : ItemSelectionModuleConfig() {
        override fun withSelectionType() = SelectionType.Multiple // Or SelectionType.Single
    }

    override fun onSelectionUpdated(selectedCount: Int) {
        // place your general selection logic here, like changing the toolbar text to indicate the selected count.
    }
}

2. Implement Selection State

Java
class SelectionStateImpl extends SelectionState<MessageModel> {
    @Override
    public boolean isSelectionEnabled(@NotNull MessageModel model) {
        return true;
    }

    @Override
    public void onSelected(@NotNull MessageModel model, boolean selected) {
        // update your model here. 
        // right after this call you will receive an onBind call in order to reflect your changes on the relevant Item Module.
        model.isSelected = selected;
    }
}
Kotlin
class SelectionStateImpl : SelectionState<MessageModel>() {
    override fun isSelectionEnabled(model: MessageModel) = true

    override fun onSelected(model: MessageModel, selected: Boolean) {
        // update your model here. 
        // right after this call you will receive an onBind call in order to reflect your changes on the relevant Item Module.
        model.isSelected = selected;
    }
}

3. Attach To ItemModule & OneAdapter

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachItemModule(new MessageModule()).addState(new SelectionStateImpl())
    .attachItemSelectionModule(new ItemSelectionModuleImpl())
    ...
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachItemModule(MessageModule()).addState(SelectionStateImpl())
    .attachItemSelectionModule(ItemSelectionModuleImpl())
    ...




Event Hooks

Item Modules can easily be enhanced with event hooks, for instance, ClickEventHook which let you bind a click listener for the entire view.

Click Event Hook

1. Implement Click Event Hook

Java
class MessageClickEvent extends ClickEventHook<MessageModel> {
    @Override
    public void onClick(@NotNull MessageModel model, @NotNull ViewBinder viewBinder) {
        // place your on click logic here.
    }
}
Kotlin
class MessageClickEvent : ClickEventHook<MessageModel>() {
    override fun onClick(model: MessageModel, viewBinder: ViewBinder) {
        // place your on click logic here.
    }
}

2. Attach To ItemModule

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachItemModule(new MessageModule()).addEventHook(new MessageClickEvent())
    ...
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachItemModule(MessageModule()).addEventHook(MessageClickEvent())
    ...



Swipe Event Hook

1. Implement Swipe Event Hook

Java
class MessageSwipeEvent extends SwipeEventHook<MessageModel> {
    @NotNull @Override
    public SwipeEventHookConfig provideHookConfig() {
        return new SwipeEventHookConfig() {
            @NotNull @Override
            public List<SwipeDirection> withSwipeDirection() {
                return Arrays.asList(SwipeDirection.Left, SwipeDirection.Right);
            }
        };
    }
    
    @Override
    public void onSwipe(@NotNull Canvas canvas, float xAxisOffset, @NotNull ViewBinder viewBinder) {
        // draw your swipe UI here.
        // like painting the canvas red with a delete icon.
    }
    @Override
    public void onSwipeComplete(@NotNull MessageModel model, @NotNull SwipeDirection direction, @NotNull ViewBinder viewBinder) {
        // place your swipe logic here.
        // like removing an item after it was swiped right.
    }
}
Kotlin
class MessageSwipeEvent : SwipeEventHook<MessageModel>() {
    override fun provideHookConfig(): SwipeEventHookConfig = object : SwipeEventHookConfig() {
        override fun withSwipeDirection() = listOf(SwipeDirection.Left, SwipeDirection.Right)
    }

    override fun onSwipe(canvas: Canvas, xAxisOffset: Float, viewBinder: ViewBinder) {
        // draw your swipe UI here.
        // like painting the canvas red with a delete icon.
    }

    override fun onSwipeComplete(model: MessageModel, direction: SwipeDirection, viewBinder: ViewBinder) {
        // place your swipe logic here.
        // like removing an item after it was swiped right.
    }
}

2. Attach To ItemModule

Java
OneAdapter oneAdapter = new OneAdapter(recyclerView)
    .attachItemModule(new MessageModule()).addEventHook(new MessageSwipeEvent())
    ...
Kotlin
val oneAdapter = OneAdapter(recyclerView)
    .attachItemModule(MessageModule()).addEventHook(MessageSwipeEvent())
    ...




Others

First Bind Animation

The provided Animator will be animated on the first bind of the corresponding ItemModule's models.

Java
class MessageModule extends ItemModule<MessageModel> {
      @NotNull @Override
      public ItemModuleConfig provideModuleConfig() {
          return new ItemModuleConfig() {
              @Override
              public int withLayoutResource() { return R.layout.message_model; }
              
              @Nullable @Override
              public Animator withFirstBindAnimation() {
                  // can be implemented by inflating Animator Xml
                  return AnimatorInflater.loadAnimator(context, R.animator.item_animation_example);
              }
          };
      }

      @Override
      public void onBind(@NotNull MessageModel model, @NotNull ViewBinder viewBinder) { ... }
}
Kotlin
class MessageModule : ItemModule<MessageModel>() {
    override fun provideModuleConfig() = object : ItemModuleConfig() {
        override fun withLayoutResource() = R.layout.message_model
        
        override fun withFirstBindAnimation(): Animator {
            // or can be implemented by constructing ObjectAnimator
            return ObjectAnimator().apply {
                 propertyName = "translationX"
                 setFloatValues(-1080f, 0f)
                 duration = 750
            }
        }
    }

    override fun onBind(model: MessageModel, viewBinder: ViewBinder) { ... }
}

Data Binding

Built in support for Android Data Binding (https://developer.android.com/topic/libraries/data-binding) Full example is provided in the example project.

Java
class MessageModule extends ItemModule<ObservableMessageModel> {
      @NotNull @Override
      public ItemModuleConfig provideModuleConfig() {
          return new ItemModuleConfig() {
              @Override
              public int withLayoutResource() { return R.layout.message_model_data_binding; }
          };
      }

      @Override
      public void onBind(@NotNull ObservableMessageModel model, @NotNull ViewBinder viewBinder) {
          ViewDataBinding binding = viewBinder.getDataBinding();
          binding.setVariable(BR.messageModel, model);
          binding.setLifecycleOwner(DataBindingActivity.class);
          binding.executePendingBindings();
      }
}
Kotlin
class MessageModule : ItemModule<ObservableMessageModel>() {
    override fun provideModuleConfig() = object : ItemModuleConfig() {
        override fun withLayoutResource() = R.layout.message_model_data_binding
    }

    override fun onBind(model: ObservableMessageModel, viewBinder: ViewBinder) {
        viewBinder.dataBinding?.run {
            setVariable(BR.messageModel, model)
            lifecycleOwner = this@DataBindingActivity
            executePendingBindings()
        }
    }
}



License

Copyright (c) 2019 Idan Atsmon

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.