public interface ItemsPositionGetter {
View getChildAt(int position);
int indexOfChild(View view);
int getPositionForView(View view);
View getViewByPosition(int position);
int getChildCount();
int getLastVisiblePosition();
int getFirstVisiblePosition();
}
public class ListViewItemPositionGetter implements ItemsPositionGetter{
private final ListView mListView;
public ListViewItemPositionGetter(ListView listView) {
mListView = listView;
}
@Override
public View getChildAt(int position) {
return mListView.getChildAt(position);
}
@Override
public int indexOfChild(View view) {
return mListView.indexOfChild(view);
}
@Override
public int getPositionForView(View view) {
return mListView.getPositionForView(view);
}
@Override
public View getViewByPosition(int position) {
final int firstListItemPosition = mListView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + mListView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition ) {
return mListView.getAdapter().getView(position, null, mListView);
} else {
final int childIndex = position - firstListItemPosition;
return mListView.getChildAt(childIndex);
}
}
@Override
public int getChildCount() {
return mListView.getChildCount();
}
@Override
public int getLastVisiblePosition() {
return mListView.getLastVisiblePosition();
}
@Override
public int getFirstVisiblePosition() {
return mListView.getFirstVisiblePosition();
}
}
public class RecyclerViewItemPositionGetter implements ItemsPositionGetter {
private static final boolean SHOW_LOGS = Config.SHOW_LOGS;
private static final String TAG = RecyclerViewItemPositionGetter.class.getSimpleName();
private LinearLayoutManager mLayoutManager;
private RecyclerView mRecyclerView;
public RecyclerViewItemPositionGetter(LinearLayoutManager layoutManager, RecyclerView recyclerView) {
mLayoutManager = layoutManager;
mRecyclerView = recyclerView;
}
@Override
public View getChildAt(int position) {
View view = mLayoutManager.getChildAt(position);
return view;
}
@Override
public int indexOfChild(View view) {
int indexOfChild = mRecyclerView.indexOfChild(view);
return indexOfChild;
}
@Override
public int getPositionForView(View view) {
return mLayoutManager.getPosition(view);//mRecyclerView.getChildAdapterPosition(view)
}
@Override
public View getViewByPosition(int position) {
return mLayoutManager.findViewByPosition(position);
}
@Override
public int getChildCount() {
int childCount = mRecyclerView.getChildCount();
return childCount;
}
@Override
public int getLastVisiblePosition() {
return mLayoutManager.findLastVisibleItemPosition();
}
@Override
public int getFirstVisiblePosition() {
return mLayoutManager.findFirstVisibleItemPosition();
}
}