Last active
January 23, 2017 12:56
-
-
Save sugoi-wada/1697557f395eaea65934914b7af65589 to your computer and use it in GitHub Desktop.
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
import android.support.v7.widget.RecyclerView | |
import android.view.View | |
import android.view.ViewGroup | |
import android.widget.ProgressBar | |
import android.widget.RelativeLayout | |
abstract class ProgressRecyclerAdapter<T : RecyclerView.ViewHolder> : RecyclerView.Adapter<RecyclerView.ViewHolder>() { | |
companion object { | |
private val VIEW_PROGRESS = 11 | |
} | |
var isProgress: Boolean = false | |
set(value) { | |
if (field == value) { | |
return | |
} | |
field = value | |
if (value) { | |
notifyItemInserted(getOriginalItemCount()) | |
} else { | |
notifyItemRemoved(getOriginalItemCount()) | |
} | |
} | |
final override fun getItemCount(): Int = getOriginalItemCount() + if (isProgress) 1 else 0 | |
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = | |
when (viewType) { | |
VIEW_PROGRESS -> { | |
val layout = RelativeLayout(parent.context).apply { | |
val padding = parent.context.resources.getDimensionPixelSize(R.dimen.spacing) | |
setPadding(padding, padding, padding, padding) | |
} | |
val layoutParams = RelativeLayout.LayoutParams(progressWidth, progressHeight).apply { | |
addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE) | |
} | |
layout.addView(ProgressBar(parent.context), layoutParams) | |
ProgressViewHolder(layout) | |
} | |
else -> onCreateOriginalViewHolder(parent, viewType) | |
} | |
abstract val progressWidth: Int | |
abstract val progressHeight: Int | |
final override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { | |
if (isProgress && position == getOriginalItemCount()) { | |
return | |
} | |
onBindOriginalViewHolder(holder as T, position) | |
} | |
final override fun getItemViewType(position: Int): Int = if (getOriginalItemCount() == position) VIEW_PROGRESS else getOriginalItemViewType(position) | |
abstract fun getOriginalItemCount(): Int | |
abstract fun onCreateOriginalViewHolder(parent: ViewGroup, viewType: Int): T | |
abstract fun onBindOriginalViewHolder(holder: T, position: Int) | |
open fun getOriginalItemViewType(position: Int): Int = 0 | |
class ProgressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment