Created
April 3, 2015 08:37
-
-
Save unosk/af99b1a97b2f48521cee to your computer and use it in GitHub Desktop.
Android RecyclerView.Adapter
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.content.Context; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.LayoutInflater; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
public abstract class ArrayAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { | |
private final Object mLock = new Object(); | |
private final Context mContext; | |
private final LayoutInflater mInflater; | |
private final List<T> mObjects = new ArrayList<>(); | |
public ArrayAdapter(Context context) { | |
mContext = context; | |
mInflater = LayoutInflater.from(context); | |
} | |
@Override | |
public int getItemCount() { | |
return mObjects.size(); | |
} | |
public T getItem(int position) { | |
return mObjects.get(position); | |
} | |
public List<T> getItems() { | |
return mObjects; | |
} | |
public void add(T object) { | |
synchronized (mLock) { | |
mObjects.add(object); | |
} | |
notifyDataSetChanged(); | |
} | |
public void insert(T object, int index) { | |
synchronized (mLock) { | |
mObjects.add(index, object); | |
} | |
notifyDataSetChanged(); | |
} | |
public void remove(T object) { | |
synchronized (mLock) { | |
mObjects.remove(object); | |
} | |
notifyDataSetChanged(); | |
} | |
public void addAll(List<T> objects) { | |
synchronized (mLock) { | |
mObjects.addAll(objects); | |
} | |
notifyDataSetChanged(); | |
} | |
public void setAll(List<T> objects) { | |
synchronized (mLock) { | |
mObjects.clear(); | |
mObjects.addAll(objects); | |
} | |
notifyDataSetChanged(); | |
} | |
public void clear() { | |
synchronized (mLock) { | |
mObjects.clear(); | |
} | |
notifyDataSetChanged(); | |
} | |
public void sort(Comparator<? super T> comparator) { | |
synchronized (mLock) { | |
Collections.sort(mObjects, comparator); | |
} | |
notifyDataSetChanged(); | |
} | |
public boolean isEmpty() { | |
return mObjects == null || mObjects.isEmpty(); | |
} | |
protected Context getContext() { | |
return mContext; | |
} | |
protected LayoutInflater getInflater() { | |
return mInflater; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment