|
1 | 1 | #AdapterCommands |
| 2 | +Drop in solution to animate RecyclerView's dataset changes by using the `command pattern. |
| 3 | +Read my [blog post]() for more information. |
| 4 | + |
| 5 | +Keep in mind that the runtime of `DiffCommandsCalculator` is `O(n*m)` (n = number of items in old list, m = number of items in new list). |
| 6 | +So you better run this on a background thread if your data set contains many items. |
2 | 7 |
|
3 | 8 | ##Dependencies |
4 | 9 |
|
5 | 10 | ```groovy |
6 | | -compile 'com.hannesdorfmann.adaptercommands:adaptercommands:1.0.0' |
| 11 | +compile 'com.hannesdorfmann.adaptercommands:adaptercommands:1.0.1' |
7 | 12 | ``` |
8 | 13 |
|
9 | | -## Motivation |
10 | | - |
11 | 14 | ## How to use |
| 15 | +There are basically 2 components: |
| 16 | + - `DiffCommandsCalculator` that calculates the difference from previous data set to the new data set and returns `List<AdapterCommand>` |
| 17 | + - `AdapterCommandProcessor` takes `List<AdapterCommand>` and executes each command to trigger RecyclerView's `ItemAnimator` to run animations. |
| 18 | + |
| 19 | +```java |
| 20 | +public class MainActivity extends AppCompatActivity { |
| 21 | + |
| 22 | + @Bind(R.id.recyclerView) RecyclerView recyclerView; |
| 23 | + |
| 24 | + List<Item> items = new ArrayList<Item>(); |
| 25 | + Random random = new Random(); |
| 26 | + ItemAdapter adapter; // RecyclerView adapter |
| 27 | + AdapterCommandProcessor commandProcessor; |
| 28 | + DiffCommandsCalculator<Item> commandsCalculator = new DiffCommandsCalculator<Item>(); |
| 29 | + |
| 30 | + @Override protected void onCreate(Bundle savedInstanceState) { |
| 31 | + super.onCreate(savedInstanceState); |
| 32 | + setContentView(R.layout.activity_main); |
| 33 | + ButterKnife.bind(this); |
| 34 | + |
| 35 | + adapter = new ItemAdapter(this, items); |
| 36 | + recyclerView.setAdapter(adapter); |
| 37 | + recyclerView.setLayoutManager(new GridLayoutManager(this, 4)); |
| 38 | + |
| 39 | + commandProcessor = new AdapterCommandProcessor(adapter); |
| 40 | + } |
| 41 | + |
| 42 | + // Called when new items should be displayed in RecyclerView |
| 43 | + public void setItems(List<Item> newItems){ |
| 44 | + adapter.setItems(newItems); |
| 45 | + List<AdapterCommand> commands = commandsCalculator.diff(items); |
| 46 | + commandProcessor.execute(commands); // executes commands that triggers animations |
| 47 | + } |
| 48 | +``` |
| 49 | + |
| 50 | +## MVP |
| 51 | +Best practise is to use a `PresentationModel` and `Model-View-Presenter`. See my [blog post]() for a concrete example. |
12 | 52 |
|
13 | 53 | ## License |
14 | 54 |
|
|
0 commit comments