• Stars
    star
    1,911
  • Rank 24,257 (Top 0.5 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework

BindingCollectionAdapter

Maven Central

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework.

Download

If you are using androidx use version 4.0.0, this also uses databinding v2

implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:4.0.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-viewpager2:4.0.0'

or use the previous stable version

implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter:2.2.0'
implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-recyclerview:2.2.0'

Usage

You need to provide your items and an ItemBinding to bind to the layout. You should use an ObservableList to automatically update your view based on list changes. However, you can use any List if you don't need that functionality.

public class ViewModel {
  public final ObservableList<String> items = new ObservableArrayList<>();
  public final ItemBinding<String> itemBinding = ItemBinding.of(BR.item, R.layout.item);
}

Then bind it to the collection view with app:items and app:itemBinding.

<!-- layout.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <import type="com.example.R" />
      <variable name="viewModel" type="com.example.ViewModel"/>
    </data>

    <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemBinding="@{viewModel.itemBinding}"/>

    <androidx.recyclerview.widget.RecyclerView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
      app:items="@{viewModel.items}"
      app:itemBinding="@{viewModel.itemBinding}"/>

    <androidx.viewpager.widget.ViewPager
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemBinding="@{viewModel.itemBinding}"/>

    <Spinner
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemBinding="@{viewModel.itemBinding}"
      app:itemDropDownLayout="@{R.layout.item_dropdown}"/>
</layout>

In your item layout, the collection item will be bound to the variable with the name you passed into the ItemBinding.

<!-- item.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <variable name="item" type="String"/>
    </data>

    <TextView
      android:id="@+id/text"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="@{item}"/>
</layout>

Note: if app:itemBinding is null, then the adapter will be set to null. This is useful if you don't have an itemBinding right away (ex: need to wait till you load data). If you aren't seeing any views, make sure you have itemBinding defined!

Multiple View Types

You can use multiple view types by using OnItemBind instead. You can still bind it to the view with app:itemBinding.

public final OnItemBind<String> onItemBind = new OnItemBind<String>() {
  @Override
  public void onItemBind(ItemBinding itemBinding, int position, String item) {
    itemBinding.set(BR.item, position == 0 ? R.layout.item_header : R.layout.item);
  }
};

If you are binding to a ListView, you must also provide the number of item types you have with app:itemTypeCount="@{2}.

Note that onItemBind is called many times so you should not do any complex processing in there. If you don't need to bind an item at a specific position (a static footer for example) you can use ItemBinding.VAR_NONE as the variable id.

Bind Extra Variables

You can bind additional variables to items in the list with itemBinding.bindExtra(BR.extra, value). This is useful for components that you don't want the items themselves to care about. For example, you can implement an item click listener as such

public interface OnItemClickListener {
    void onItemClick(String item);
}

OnItemClickListener listener = ...;
ItemBinding<Item> itemBinding = ItemBinding.<Item>of(BR.item, R.layout.item)
    .bindExtra(BR.listener, listener);
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <variable name="item" type="String"/>
      <variable name="listener" type="OnItemClickListener"/>
    </data>

    <TextView
      android:id="@+id/text"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:onClick="@{() -> listener.onItemClick(item)}"
      android:text="@{item}"/>
</layout>

Additional Adapter Configuration

ListView

You can set a callback to give an id for each item in the list with

adapter.setItemIds(new BindingListViewAdapter.ItemIds<T>() {
  @Override
  public long getItemId(int position, T item) {
    return // Calculate item id.
  }
});

or by defining app:itemIds="@{itemIds}" in the ListView in your layout file. Setting this will make hasStableIds return true which can increase performance of data changes.

You can set a callback for isEnabled() as well with

adapter.setItemEnabled(new BindingListViewAdapter.ItemEnabled<T>() {
  @Override
  public boolean isEnabled(int position, T item) {
    return // Calculate if item is enabled.
  }
});

or by defining app:itemEnabled="@{itemEnabled}"in the ListView in you layout file.

ViewPager

You can set a callback to give a page title for each item in the list with

adapter.setPageTitles(new PageTitles<T>() {
  @Override
  public CharSequence getPageTitle(int position, T item) {
    return "Page Title";
  }
});

or by defining app:pageTitles="@{pageTitles}" in the ViewPager in your layout file.

RecyclerView

You can construct custom view holders with

adapter.setViewHolderFactory(new ViewHolderFactory() {
  @Override
  public RecyclerView.ViewHolder createViewHolder(ViewDataBinding binding) {
    return new MyCustomViewHolder(binding.getRoot());
  }
});

or by defining app:viewHolder="@{viewHolderFactory}" in the RecyclerView in your layout file.

Directly manipulating views

Data binding is awesome and all, but you may run into a case where you simply need to manipulate the views directly. You can do this without throwing away the whole of databinding by subclassing an existing BindingCollectionAdapter. You can then bind adapter in your layout to your subclass's class name to have it use that instead. Instead of overriding the normal adapter methods, you should override onCreateBinding() or onBindBinding() and call super allowing you to run code before and after those events and get access to the item view's binding.

public class MyRecyclerViewAdapter<T> extends BindingRecyclerViewAdapter<T> {

  @Override
  public ViewDataBinding onCreateBinding(LayoutInflater inflater, @LayoutRes int layoutId, ViewGroup viewGroup) {
    ViewDataBinding binding = super.onCreateBinding(inflater, layoutId, viewGroup);
    Log.d(TAG, "created binding: " + binding);
    return binding;
  }

  @Override
  public void onBindBinding(ViewDataBinding binding, int bindingVariable, @LayoutRes int layoutId, int position, T item) {
    super.onBindBinding(binding, bindingVariable, layoutId, position, item);
    Log.d(TAG, "bound binding: " + binding + " at position: " + position);
  }
}
<androidx.recyclerview.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
  app:items="@{viewModel.items}"
  app:itemBinding="@{viewModel.itemBinding}"
  app:adapter="@{viewModel.adapter}"/>

Note: databinding will re-evaluate expressions in your layout each time there is a data source change. If you are using a custom adapter you should ensure you are returning the same instance each time or your scroll position etc will not be preserved.

OnItemBind helpers

There are a few classes to help with common implementations of OnItemBind.

OnItemBindClass binds an item based on the class of the item in the list.

itemBind = new OnItemBindClass<>()
  .map(String.class, BR.name, R.layout.item_name)
  .map(Footer.class, ItemBinding.VAR_NONE, R.layout.item_footer)
  .map(Item.class, new OnItemBind<Item>() {
                       @Override
                       public void onItemBind(ItemBinding itemBinding, int position, Item item) {
                         itemBinding.clearExtras()
                                    .set(BR.item, position == 0 ? R.layout.item_header : R.layout.item)
                                    .bindExtra(BR.extra, (list.size() - 1) == position);
                       }
                     })
  .map(Object.class, ItemBinding.VAR_NONE, R.layout.item_other);

OnItemBindModel delegates to the items in the list themselves to determine the binding.

itemBind = new OnItemBindModel<Model>();

public class Model implements ItemBindingModel {
  @Override
  public void onItemBind(ItemBinding itemBinding) {
    itemBinding.set(BR.name, R.layout.item_name);
  }
}

MergeObservableList

There are many times you want to merge multiple data sources together. This can be as simple as adding headers and footers or as complex as concatenating multiple data sources. It is hard to manage these lists yourself since you have to take into account all items when updating a subset.

MergeObservableList solves this by giving you a "merged" view of your data sources.

ObservableList<String> data = new ObservableArrayList<>();
MergeObservableList<String> list = new MergeObservableList<>()
  .insertItem("Header")
  .insertList(data)
  .insertItem("Footer");

data.addAll(Arrays.asList("One", "Two"));
// list => ["Header", "One", "Two", "Footer"]
data.remove("One");
// list => ["Header", "Two", "Footer"]

DiffObservableList

Say you want to update list 'a' to list 'b' and you don't want to calculate what has changed between the two manually.

DiffObservableList builds off of DiffUtil to automatically calculate the changes between two lists.

DiffObservableList<Item> list = new DiffObservableList(new DiffObservableList.Callback<Item>() {
    @Override
    public boolean areItemsTheSame(Item oldItem, Item newItem) {
        return oldItem.id.equals(newItem.id);
    }

    @Override
    public boolean areContentsTheSame(Item oldItem, Item newItem) {
        return oldItem.value.equals(newItem.value);
    }
});

list.update(Arrays.asList(new Item("1", "a"), new Item("2", "b1")));
list.update(Arrays.asList(new Item("2", "b2"), new Item("3", "c"), new Item("4", "d"));

With large lists diffing might be too costly to run on the main thread. In that case you can calculate the diff on a background thread.

DiffObservableList<Item> list = new DiffObservableList(...);

// On background thread:
DiffUtil.DiffResult diffResult = list.calculateDiff(newItems);

// On main thread:
list.update(newItems, diffResult);

Paging

Paging is supported through the bindingcollectionadapter-paging artifact. First add it to your project

implementation 'me.tatarka.bindingcollectionadapter2:bindingcollectionadapter-paging:3.1.1'

Then bind a PagedList and DiffUtil.ItemCallback.

LiveData<PagedList<Item>> pagedList = new LivePagedListBuilder<>(..., 20);
DiffUtil.ItemCallback<Item> diff = ...;
<androidx.recyclerview.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
  app:items="@{pagedList}"
  app:itemBinding="@{itemBinding}"
  app:diffConfig="@{diff}" />

Known Issues

Cannot Resolve the libraries @BindingAdapter's

This is likely because you are using the android-apt plugin which broke this in previous versions. Update to 1.6+ to fix it.

View's adapter is null

If you attempt to retrieve an adapter from a view right after binding it you may find it is null. This is because databinding waits for the next draw pass to run to batch up changes. You can force it to run immediately by calling binding.executePendingBindings().

LiveData not working

Live data support has been added in 2.3.0-beta3 and 3.0.0-beta3 (androidx). For most cases it should 'just work'. However, it uses a bit of reflection under the hood and you'll have to call adapter.setLifecycleOwner(owner) if your containing view does not use databinding. This will be fixed whenever this issue gets resolved.

License

Copyright 2015 Evan Tatarka

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.

More Repositories

1

gradle-retrolambda

A gradle plugin for getting java lambda support in java 6, 7 and android
Java
5,315
star
2

kotlin-inject

Dependency injection lib for kotlin
Kotlin
1,165
star
3

JobSchedulerCompat

[Deprecated] A backport of Android Lollipop's JobScheduler to api 10+
Java
735
star
4

rxloader

[Deprecated] Handles Android's activity lifecyle for rxjava's Observable
Java
322
star
5

android-studio-unit-test-plugin

[Deprecated] Android Studio IDE support for Android gradle unit tests. Prepared for Robolectric.
Java
235
star
6

holdr

[Deprecated] Because typing findViewById() in Android is such a pain.
Java
208
star
7

redux

Redux ported to java/android (name tbd)
Java
192
star
8

android-retrolambda-lombok

A modified version of lombok ast that allows lint to run on java 8 sources without error.
Java
175
star
9

compose-collapsable

A generic collapsable implementation with dragging and nested scrolling support
Kotlin
91
star
10

compose-shown

Provides a callback for when a @Composable is shown to the user
Kotlin
65
star
11

injectedvmprovider

Small lib to use easily use Android's ViewModels with a depedency injection framework like dagger
Java
51
star
12

yield-layout

Combine layouts in Android, opposite of how <include/> works.
Java
50
star
13

gsonvalue

Compile-time generation of gson TypeAdapters to preserve class encapsulation
Java
42
star
14

simplefragment

A fragment-like abstraction for Android that is easier to use and understand
Java
41
star
15

streamqflite

flutter reactive stream wrapper around sqflite inspired by sqlbrite
Dart
40
star
16

android-shard

'Fragments' with a simpler api built on top of the android architecture components
Java
29
star
17

studio-splash

An archive of all the Android Studio splash images
Kotlin
26
star
18

timesync

Android library for periodicly syncing data from server.
Java
25
star
19

android-quiznos

Sad about the boring Android 10 naming? This lib give you some options to spice things up.
Java
23
star
20

PokeMVVM

A playground for MVVM style architecture on Android
Java
17
star
21

parsnip

A modern XML library for Android and Java
Java
15
star
22

kotlin-inject-samples

Verious samples using kotlin-inject
Kotlin
15
star
23

android-biometrics-compat-issue

A sample implementation of the androidx biometric compat lib with all the workarounds needed for a production app
Kotlin
15
star
24

loadie

Android Loaders for the rest of us
Java
14
star
25

retain-state

A dead simple way to retain some state thought configuration changes on Android
Java
12
star
26

spanalot

A simple utility for creating and modifying spannables in Android
Java
11
star
27

wiiafl

Wrap it in a FrameLayout
Kotlin
10
star
28

recyclerview-sample

An example of how to use Android L's new RecyclerView with a custom ItemAnimator
Java
10
star
29

voice-changer

Playing around with real-time audio processing on andriod with rust
Kotlin
9
star
30

fragstack

A better android fragment backstack
Kotlin
9
star
31

android-apngrs

Android bindings to image-rs for APNG support.
Kotlin
8
star
32

NyandroidRestorer

Restore our favorite pop-tart-rainbow friend in Android Studio.
Java
7
star
33

android-safe-rxjava-usage

An example of safely using rxjava on Android
Java
7
star
34

nav

A simple declarative Android compose navigator
Kotlin
7
star
35

jackport

Backporting java 8 apis to older versions of android using the jack plugin system.
Java
7
star
36

kotlin-fragment-dsl

A nice kotlin dsl for dealing with the fragment backstack.
Kotlin
7
star
37

sres

Super-Duper Android Layout Preprocessor
Java
6
star
38

assertk

This project has moved to https://github.com/willowtreeapps/assertk
Kotlin
6
star
39

auto-value-lens

AutoValue extension to create lenses for AutoValue properties
Kotlin
5
star
40

flutter_study

Flashcard app written in flutter
Dart
5
star
41

fasax

The fastest way to unmarshall XML to Java on Android
Java
5
star
42

value-processor

Helper for creating annotation processors that create/read value objects.
Kotlin
5
star
43

sparkle

A compiler for FiM++ written in rust
Rust
5
star
44

webpush-fcm-relay

Relays WebPush messages to Firebase Cloud Messaging
Kotlin
5
star
45

typedbundle

Typesafe key-value parinings for Android Bundles.
Java
4
star
46

animated-spans

Playing arround with animating spans in an EditText
Java
4
star
47

silent-support

Backport new android api calls to support lib versions.
Java
4
star
48

FitTextView

Android TextView that scales text to fit area
Java
3
star
49

webpush-encryption

A lightweight webpush encryption/decryption library
Kotlin
3
star
50

kotlin-ir-plugin-example

Playinig around with kotlin ir plugin support added for compose
Kotlin
3
star
51

ipromise

small proimse/future library for java and Android
Java
3
star
52

quickreturn-listview

A quickreturn for a listview in android
Java
3
star
53

yesdata

Errorprone check to verify you have implemented data classes correctly.
Java
3
star
54

domain-mapper

Generates code to map from one domain object to another
Kotlin
3
star
55

kotlin-inject-android

Android extensions to kotlin-inject
Kotlin
2
star
56

named-semaphore

Safe wrapper of libc's named semaphores
Rust
2
star
57

viewpager2stateissue

Kotlin
2
star
58

vimrc

Vim Script
2
star
59

google-actions-wolfram

Query Wolfram Alpha using Google Actions api
JavaScript
2
star
60

gradle-central-release-publishing

An opinionated gradle plugin to manage publishing to maven central
Kotlin
2
star
61

autodata

An extensable alternative to AutoValue.
Java
2
star
62

ponysay-rust

A barebones port of ponysay to rust.
Rust
2
star
63

.emacs.d

My emacs config
JavaScript
2
star
64

RxJavaLeak

A sample project showing a memory leak in RxJava
Java
2
star
65

res

Commandline res manager for android
Rust
2
star
66

fragment-recreator

A utility to handle fragment view-recreation when used in an Activity that handles configuration changes
Kotlin
2
star
67

crequire

A simple way to require c code in ruby using SWIG
Ruby
2
star
68

adp

Android Device Pool
Rust
1
star
69

fragment-view-issue

Kotlin
1
star
70

recyclerview-issue2

Kotlin
1
star
71

android-gradle-jack-plugin

Fork of the android gradle plugin that supports jack plugins
Java
1
star
72

blog

HTML
1
star
73

paging-issue

Kotlin
1
star
74

instance_state

[WIP] Flutter plugin to save/restore instance state on Android
Dart
1
star
75

app-test

Kotlin
1
star
76

android-scroll-to-position-test

Testing how often onBindViewHolder is called when using scrollToPosition() on recyclerview
Java
1
star
77

wordlists

A web application to create and use large lists of words
Ruby
1
star
78

studio-dep-sub-issue

Build failure when using a dependencySubstitution
Java
1
star
79

kotlin-mpp-ui-test

Expirmental cross-platform ui tests with kotlin multiplatform
Swift
1
star
80

placeholder-edittext

Java
1
star
81

prime-multiples

Code for MPMP 19 in rust https://www.think-maths.co.uk/19challenge
Rust
1
star
82

docker-compose-test

A helper to run integration tests with docker-compose
Rust
1
star
83

recyclerview-predraw-issue

Issue with recyclerview animations and predraw listeners
Java
1
star
84

paging-compose-refresh-issue

Kotlin
1
star
85

compose-dialog-window-insets-issue

Kotlin
1
star