Giter Site home page Giter Site logo

thuytrinh / binding-collection-adapter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from evant/binding-collection-adapter

0.0 2.0 0.0 306 KB

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

License: Apache License 2.0

Java 100.00%

binding-collection-adapter's Introduction

BindingCollectionAdapter

Maven Central

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

Download

compile 'me.tatarka.bindingcollectionadapter:bindingcollectionadapter:1.1.0'
compile 'me.tatarka.bindingcollectionadapter:bindingcollectionadapter-recyclerview:1.1.0'

requires at least android gradle plugin 1.5.0.

Usage

You need to provide your items and an ItemView 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 ItemView itemView = ItemView.of(BR.item, R.layout.item);
}

Then bind it to the collection view with app:items and app:itemView. There are also some convience factories to attach a LayoutManager to a RecyclerView with app:layoutManager.

<!-- layout.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <variable name="viewModel" type="com.example.ViewModel"/> 
      <import type="me.tatarka.bindingcollectionadapter.LayoutManagers" />
    </data>
    
    <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>
      
    <android.support.v7.widget.RecyclerView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="@{LayoutManagers.linear()}"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>
      
    <android.support.v4.view.ViewPager
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>
      
    <Spinner
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"
      app:dropDownItemView="@{viewModel.dropDownItemView}"/>
</layout>

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

<!-- 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>

Multiple View Types

You can use multiple view types by using a ItemViewSelector instead. You can still bind it to the view with app:itemView.

public final ItemViewSelector<String> itemView = new BaseItemViewSelector<String>() {
    @Override
    public void select(ItemView itemView, int position, String item) {
        itemView.set(BR.item, position == 0 ? R.layout.item_header : R.layout.item);
    }
    
    // You need to override this method when using a ListView as it requires to know how
    // many view types there are immedeatly. RecyclerView and ViewPager don't need this.
    @Override
    public int viewTypeCount() {
      return 2;
    }
};

Note that select 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 ItemView.BINDING_VARIABLE_NONE as the binding varibale.

Additonal 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.

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> {
    public LoggingRecyclerViewAdapter(@NonNull ItemViewArg<T> arg) {
      super(arg);
    }

    @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);
    }
}
<android.support.v7.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layoutManager="@{LayoutManagers.linear()}"
  app:items="@{viewModel.items}"
  app:itemView="@{viewModel.itemView}"
  app:adapter='@{"com.example.MyRecyclerViewAdapter"}'/>

You can also use a factory instead of the class name. This allows you to not have reflection and gives you more control over it's construction.

public static final BindingRecyclerViewAdapterFactory MY_FACTORY = new BindingRecyclerViewAdapterFactory() {
  @Override
  public <T> BindingRecyclerViewAdapter<T> create(RecyclerView recyclerView, ItemViewArg<T> arg) {
    return new MyRecyclerViewAdapter<>(arg);
  }
}
<android.support.v7.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layoutManager="@{LayoutManagers.linear()}"
  app:items="@{viewModel.items}"
  app:itemView="@{viewModel.itemView}"
  app:adapter="@{MY_FACTORY}"/>

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().

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.

binding-collection-adapter's People

Contributors

evant avatar kamiox avatar okhoshi avatar saleehk avatar vkotovv avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.