Created
July 20, 2017 12:45
-
-
Save kubode/d2922d0c26160a53955e0143e422bb35 to your computer and use it in GitHub Desktop.
DiffUtilを使ってRecyclerView.Adapterをいい感じにする ref: http://qiita.com/kubode/items/92c1190a6421ba055cc0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Diffable { | |
// otherと同じIDを持つかどうか | |
fun isTheSame(other: Diffable): Boolean = equals(other) | |
// otherと完全一致するかどうか | |
fun isContentsTheSame(other: Diffable): Boolean = equals(other) | |
} | |
private class Callback( | |
val old: List<Diffable>, | |
val new: List<Diffable> | |
) : DiffUtil.Callback() { | |
override fun getOldListSize() = old.size | |
override fun getNewListSize() = new.size | |
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return old[oldItemPosition].isTheSame(new[newItemPosition]) | |
} | |
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return old[oldItemPosition].isContentsTheSame(new[newItemPosition]) | |
} | |
} | |
fun calculateDiff( | |
old: List<Diffable>, | |
new: List<Diffable>, | |
detectMoves: Boolean = false | |
): DiffUtil.DiffResult { | |
return DiffUtil.calculateDiff(Callback(old, new), detectMoves) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyAdapter : RecyclerView.Adapter<AbstractViewHolder>() { | |
var items: List<Item> by Delegates.observable(emptyList()) { _, old, new -> | |
calculateDiff(old, new).dispatchUpdatesTo(this) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val adapter = MyAdapter() | |
recyclerView.adapter = adapter | |
adapter.items = listOf(Item(0, "Item: 0")) | |
recyclerView.postDelayed({ adapter.items += Item(1, "Item: 1") }, 1000) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Item(val id: Long, val fullName: String) : Diffable { | |
override fun isTheSame(other: Diffable) = id == (other as? Item)?.id | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment