Last active
March 25, 2016 05:52
-
-
Save yrom/8d8e59cd2fb8f8365d78 to your computer and use it in GitHub Desktop.
wrap android.support.v7.widget.RecyclerView.Adapter like android.widget.ListAdapter
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 java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collection; | |
import java.util.List; | |
import android.content.Context; | |
import android.support.v7.widget.RecyclerView.ViewHolder; | |
public abstract class ArrayAdapter<T, VH extends ViewHolder> extends BaseAdapter<T, VH> { | |
private List<T> mItems; | |
private Context mContext; | |
private Object mLock = new Object(); | |
private boolean mNotifyOnChange = true; | |
public ArrayAdapter(Context context) { | |
this(context, new ArrayList<T>()); | |
} | |
public ArrayAdapter(Context context, T... items) { | |
this(context, Arrays.asList(items)); | |
} | |
public ArrayAdapter(Context context, List<T> items) { | |
mContext = context; | |
mItems = items; | |
} | |
public Context getContext() { | |
return mContext; | |
} | |
@Override | |
public T getItem(int position) { | |
return mItems.get(position); | |
} | |
public final void setNotifyOnChange(boolean notifyOnChange) { | |
mNotifyOnChange = notifyOnChange; | |
} | |
private final void notifyDataSetChangedIfNeed(){ | |
if(mNotifyOnChange) notifyDataSetChanged(); | |
} | |
public void add(T item){ | |
synchronized (mLock) { | |
mItems.add(item); | |
} | |
if(mNotifyOnChange) notifyItemInserted(mItems.lastIndexOf(item)); | |
} | |
public void addAll(Collection<T> items){ | |
synchronized (mLock) { | |
mItems.addAll(items); | |
} | |
notifyDataSetChangedIfNeed(); | |
} | |
public void add(int position, T item){ | |
synchronized (mLock) { | |
mItems.add(position, item); | |
} | |
if(mNotifyOnChange) notifyItemInserted(position); | |
} | |
public void remove(T item){ | |
synchronized (mLock) { | |
mItems.remove(item); | |
} | |
notifyDataSetChangedIfNeed(); | |
} | |
public void clear(){ | |
synchronized (mLock) { | |
mItems.clear(); | |
} | |
notifyDataSetChangedIfNeed(); | |
} | |
@Override | |
public int getItemCount() { | |
return mItems.size(); | |
} | |
} |
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.Adapter; | |
import android.support.v7.widget.RecyclerView.ViewHolder; | |
public abstract class BaseAdapter<T, VH extends ViewHolder> extends Adapter<VH> { | |
public abstract T getItem(int position); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment