From 45b64b886467d9e5128827e2161540e8d69a0545 Mon Sep 17 00:00:00 2001 From: Sosuke Masui Date: Sun, 18 Sep 2016 14:16:24 +0900 Subject: [PATCH] Fixed to set mPosition to ViewHolder --- .../support/v7/widget/ViewHolderDelegate.java | 12 ++++++++++ .../LoopRecyclerViewPagerAdapter.java | 23 ++----------------- 2 files changed, 14 insertions(+), 21 deletions(-) create mode 100644 lib/src/main/java/android/support/v7/widget/ViewHolderDelegate.java diff --git a/lib/src/main/java/android/support/v7/widget/ViewHolderDelegate.java b/lib/src/main/java/android/support/v7/widget/ViewHolderDelegate.java new file mode 100644 index 0000000..950def7 --- /dev/null +++ b/lib/src/main/java/android/support/v7/widget/ViewHolderDelegate.java @@ -0,0 +1,12 @@ +package android.support.v7.widget; + +public abstract class ViewHolderDelegate { + + private ViewHolderDelegate() { + throw new UnsupportedOperationException("no instances"); + } + + public static void setPosition(RecyclerView.ViewHolder viewHolder, int position) { + viewHolder.mPosition = position; + } +} diff --git a/lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPagerAdapter.java b/lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPagerAdapter.java index 07a58e3..fa8ef1e 100644 --- a/lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPagerAdapter.java +++ b/lib/src/main/java/com/lsjwzh/widget/recyclerviewpager/LoopRecyclerViewPagerAdapter.java @@ -1,17 +1,12 @@ package com.lsjwzh.widget.recyclerviewpager; import android.support.v7.widget.RecyclerView; -import android.util.Log; +import android.support.v7.widget.ViewHolderDelegate; -import java.lang.reflect.Field; public class LoopRecyclerViewPagerAdapter extends RecyclerViewPagerAdapter { - private static final String TAG = LoopRecyclerViewPager.class.getSimpleName(); - - private Field mPositionField; - public LoopRecyclerViewPagerAdapter(RecyclerViewPager viewPager, RecyclerView.Adapter adapter) { super(viewPager, adapter); } @@ -48,21 +43,7 @@ public void onBindViewHolder(VH holder, int position) { super.onBindViewHolder(holder, getActualPosition(position)); // because of getCurrentPosition may return ViewHolder‘s position, // so we must reset mPosition if exists. - if (mPositionField == null) { - try { - mPositionField = holder.getClass().getDeclaredField("mPosition"); - mPositionField.setAccessible(true); - } catch (NoSuchFieldException e) { - Log.i(TAG, "The holder doesn't have a mPosition field."); - } - } - if (mPositionField != null) { - try { - mPositionField.set(holder, position); - } catch (Exception e) { - Log.w(TAG, "Error while updating holder's mPosition field", e); - } - } + ViewHolderDelegate.setPosition(holder, position); } public int getActualPosition(int position) {