진행중인 프로젝트에서 아이템이 추가 될 때 마다 새로 생긴 아이템에 animation 효과 (alpha 0->1) 를 줘야했다.
1.
가장 기본적인 방법으로,
recyclerview에는 defaultItemAnimator가 설정되어 있기 때문에 간단하게 animation효과를 줄 수 있다.
val defaultItemAnimator = DefaultItemAnimator()
defaultItemAnimator.addDuration = 1500
defaultItemAnimator.removeDuration = 1000
recyclerView.itemAnimator = defaultItemAnimator
아이템이 추가 혹은 삭제 될 때 마다 설정해놓은 duration 값 만큼 alpha값이 0->1로 증가하며 item이 나타난다.

그러나 이러한 방식은 하나의 recyclerview의 animation이 전부 통일되어 나타난다.
진행중인 프로젝트에서 목표는 특정 viewtype에 대해서는 animation이 나타나지 않거나, 다른 효과를 줘야 했다.
2.
viewHolder에 따라 다른 animation 효과를 주는 방법
class ModelRecyclerAdapter<M: Model, VM: BaseViewModel>(
private var modelList: List<Model>,
private val viewModel: VM,
private val resourcesProvider: ResourcesProvider,
private val adapterListener: AdapterListener,
private val customAnimation: CustomAnimation? = null
): ListAdapter<Model, ModelViewHolder<M>>(Model.DIFF_CALLBACK) {
private var lastPosition = -1
override fun getItemCount(): Int = modelList.size
override fun getItemViewType(position: Int): Int = modelList[position].type.ordinal
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModelViewHolder<M> {
return ModelViewHolderMapper.map(parent, CellType.values()[viewType], viewModel, resourcesProvider)
}
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(holder: ModelViewHolder<M>, position: Int) {
with(holder) {
bindData(modelList[position] as M)
bindViews(modelList[position] as M, adapterListener)
setAnimation(holder, position)
}
}
override fun submitList(list: List<Model>?) {
list?.let { modelList = it }
super.submitList(list)
}
private fun setAnimation(holder: ModelViewHolder<M>, position: Int) {
if(position > lastPosition) {
val viewType = modelList[position].type
when(viewType) {
CellType.SCRIPT_CELL -> holder.itemView.animation = customAnimation?.scriptAnimation()
else -> Unit
}
lastPosition = position
}
}
}
(recyclerview adpater를 재활용하기 위해 사전에 정의한 enum class CellType에 따라 viewholder가 달라진다)
class DefaultCustomAnimation(): CustomAnimation {
override fun scriptAnimation(): AlphaAnimation {
val anim = AlphaAnimation(0f,1f)
anim.duration = 1500
return anim
}
}
이처럼 adpater에 사전에 viewHolder에 따라 animation 효과를 따로 설정해놓을 수도 있다.
또한 기존의 recyclerivew에 내장된 defaultItemAnimator보다 좀 더 custom하게 효과를 줄 수 있다.

코드 전문:
https://github.com/YeseopLee/SkillTest/tree/feature/RecyclerviewAnimation
GitHub - YeseopLee/SkillTest
Contribute to YeseopLee/SkillTest development by creating an account on GitHub.
github.com
Reference:
'Android > Tips' 카테고리의 다른 글
| CompileSdk, TargetSdk, MinSdkVersion 비교 (0) | 2021.12.16 |
|---|---|
| 툴바(ToolBar) 구현, Toolbar VS Layout (0) | 2021.12.13 |
| Recyclerview adapter 재활용하기 (0) | 2021.11.15 |
| TabLayout (0) | 2021.11.15 |
| Retrofit2 Multiple BaseUrl (Java) (0) | 2021.03.25 |