Last active
January 12, 2018 17:31
-
-
Save sagar2093/210b09cfe877148a8565eb36f743516b to your computer and use it in GitHub Desktop.
RecyclerView plus Kotlin
This file contains 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 AutoUpdatableAdapter { | |
fun <T> RecyclerView.Adapter<*>.autoNotify(old: List<T>, new: List<T>, compare: (T, T) -> Boolean) { | |
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() { | |
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return compare(old[oldItemPosition], new[newItemPosition]) | |
} | |
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return old[oldItemPosition] == new[newItemPosition] | |
} | |
override fun getOldListSize() = old.size | |
override fun getNewListSize() = new.size | |
}) | |
diff.dispatchUpdatesTo(this) | |
} | |
} |
This file contains 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
fun RecyclerView.initRecycler(mAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>, | |
addDivider: Boolean = false, | |
spanCount: Int = 1, | |
@AnimRes animRes: Int = R.anim.layout_animation_fall_down, | |
spacing: Int = 32) = | |
this.apply { | |
layoutManager = if (spanCount == 1) LinearLayoutManager(context) else GridLayoutManager(context, spanCount) | |
layoutAnimation = AnimationUtils.loadLayoutAnimation(context, animRes) | |
if (spanCount == 1 && addDivider) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) | |
if (spacing != 0 && !addDivider) addItemDecoration(EqualSpacingItemDecoration(spacing))// 16px. In practice, you'll want to use getDimensionPixelSize | |
adapter = mAdapter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment