Skip to content

Instantly share code, notes, and snippets.

@vovkab
Last active February 25, 2017 00:59
Show Gist options
  • Save vovkab/5c447fb9bd39edec9fda37f75d3c72c0 to your computer and use it in GitHub Desktop.
Save vovkab/5c447fb9bd39edec9fda37f75d3c72c0 to your computer and use it in GitHub Desktop.
Tools for RecyclerMergeAdapter
/**
* Calculates correct item position based on RecyclerAdapter and ViewHolder adapter position.
* Takes in consideration RecyclerMergeAdapter and adjust position accordingly
*
* @param adapter RecyclerAdapter with access to RecyclerView instance
* @param viewHolder ViewHolder that was created by @adapter
* @return adjusted local position for viewHolder
*/
public static int getLocalPosition(RecyclerAdapter adapter, RecyclerView.ViewHolder viewHolder) {
int position = viewHolder.getAdapterPosition();
if (position == RecyclerView.NO_POSITION) {
// ViewHolder is in transition, data is not available
return RecyclerView.NO_POSITION;
}
final RecyclerView recyclerView = adapter.getRecyclerView();
if (recyclerView == null) {
// Adapter is not attached
return RecyclerView.NO_POSITION;
}
final RecyclerView.Adapter mainAdapter = recyclerView.getAdapter();
// Small optimization to avoid unnecessary calls for instanceOf
if (adapter == mainAdapter) {
return position;
}
if (mainAdapter instanceof RecyclerMergeAdapter) {
final RecyclerMergeAdapter mergeAdapter = (RecyclerMergeAdapter) mainAdapter;
position = mergeAdapter.getLocalPosition(position);
if (position == RecyclerView.NO_POSITION) {
// Something wrong with position
return RecyclerView.NO_POSITION;
}
}
return position;
}
/**
* Calculates local adapter position from global position in MergeAdapter
*
* @param globalPosition - global position in merge adapter
* @return position local for current adapter
*/
public int getLocalPosition(int globalPosition) {
int positionStart = 0;
int positionEnd = 0;
for (Adapter adapter : getActiveItems()) {
positionEnd += positionStart + adapter.getItemCount();
if (globalPosition >= positionStart && globalPosition < positionEnd) {
return globalPosition - positionStart;
} else {
positionStart = positionEnd;
}
}
return NO_POSITION;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment