I have a following class(I pass another recycler view adapter to a constructor):
class BaseAdapter<T>(private var items: ArrayList<T?>, private val adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>): RecyclerView.Adapter<RecyclerView.ViewHolder>()
Is it possible to not pass items directly and get them from adapter?
I don't want to pass items again and want to get them from an adapter.
private var adapter: RecyclerViewAdapter? = null
adapter = RecyclerViewAdapter(items!!, applicationContext) // another adapter, can be any
recyclerView.layoutManager = layoutManager
recyclerView.adapter = BaseAdapter(items, adapter!!)
As you see, I pass items two times, because I need to work with them in a new adapter, like
override fun showAd(firstVisibleItemPosition: Int) {
if(isInsertionNeeded){
items.add(firstVisibleItemPosition + 1, null)
setVisibleItemPos(firstVisibleItemPosition + 1)
notifyItemInserted(firstVisibleItemPosition+1)
isInsertionNeeded = false
}
}
You have to create BaseRecyclerViewAdapter like this:-
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter implements AppConstants {
public SmartArrayList<T> mArrayList;
public Context mContext;
private int margin;
public BaseRecyclerViewAdapter(Context mContext) {
this.mArrayList = new SmartArrayList<>();
this.mContext = mContext;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(getView(), parent, false);
return getViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if (mArrayList != null && mArrayList.size() > 0) {
final T obj = mArrayList.get(holder.getAdapterPosition());
setData(holder, obj, position);
}
}
#Override
public int getItemCount() {
return mArrayList.size();
}
public abstract RecyclerView.ViewHolder getViewHolder(View view);
public abstract int getView();
public abstract void setData(RecyclerView.ViewHolder holder, T data, int position);
public void addAll(ArrayList<T> mArrayList) {
if (null != mArrayList) {
this.mArrayList.addAll(mArrayList);
notifyItemRangeInserted(getItemCount(), mArrayList.size());
}
}
public void updateAll(ArrayList<T> mArrayList) {
this.mArrayList = new SmartArrayList<>();
this.mArrayList.addAll(mArrayList);
notifyDataSetChanged();
// notifyItemRangeInserted(getItemCount(), mArrayList.size());
}
public void clear() {
this.mArrayList.clear();
notifyDataSetChanged();
}
public void update(int position, T obj) {
this.mArrayList.set(position, obj);
notifyItemChanged(position);
}
public void remove(int position) {
this.mArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mArrayList.size());
}
public void add(T obj) {
int position = mArrayList.size();
this.mArrayList.add(obj);
notifyItemInserted(position);
}
public void add(int position, T obj) {
this.mArrayList.add(obj);
notifyItemInserted(position);
}
public SmartArrayList<T> getData() {
return mArrayList;
}
}
Using......
public class YourAdapterName extends BaseRecyclerViewAdapter{
Your Code......
}
And you easily get the data.
public T getItem(int position) {
return items.get(position);
}
In RecyclerView Adapter Get The List Item Using RecyclerView Adapter getItem() Method.
Send The Position And Get The Item From List.
Related
I have a RecyclerView in which the user can drag and drop an item to a different position in the RecyclerView.
So far everything works fine.
My problem begins when the RecyclerView has more items than it can display. So when it recycle his content. When the user drag and drop an item to a different position and than scroll away from this part the position changes are not saved. The user just see the old positions for the items.
You can see this issue in the .gif below.
I already tried several things out like:
recyclerViewItem.getRecycledViewPool().setMaxRecycledViews(0,0);
recyclerViewItem.setItemViewCacheSize(30);
and
holder.setIsRecyclable(false);
inside of my onBindViewHolder.
But nothing seems to work for me.
Does anyone know a solution for this problem?
My Fragment class:
public class ShoppinglistFragment extends Fragment {
private ViewModel viewModel;
private ShoppinglistAdapter adapterShoppingItem = new ShoppinglistAdapter();
private RecyclerView recyclerViewItem;
private Boolean fragmentStarted = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shoppinglist_layout, container, false);
recyclerViewItem = view.findViewById(R.id.recyclerViewShoppinglist);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(getActivity()).get(ViewModel.class);
fragmentStarted = true;
recyclerViewItem.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerViewItem.setHasFixedSize(false);
recyclerViewItem.getRecycledViewPool().setMaxRecycledViews(0,0);
recyclerViewItem.setItemViewCacheSize(30);
recyclerViewItem.setAdapter(adapterShoppingItem);
ItemTouchHelper.Callback callback =
new ItemMoveCallback(adapterShoppingItem);
ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
touchHelper.attachToRecyclerView(recyclerViewItem);
//fetch all Shoppinglist Items from local storage
viewModel.getAllShoppinglistItems().observe((LifecycleOwner) this, new Observer <List<Shoppinglist>>() {
#Override
public void onChanged(#Nullable List<Shoppinglist> items) {
if (fragmentStarted){
adapterShoppingItem.submitList(items);
fragmentStarted = false;
}
}
});
adapterShoppingItem.setOnPositionChanged(new ShoppinglistAdapter.onPositionChanged() {
#Override
public void onPositionChanged(Shoppinglist fromItem, Shoppinglist toItem, int fromPosition, int toPosition) {
int fromPositionServer = fromItem.getPosition();
int toPositionServer = toItem.getPosition();
fromItem.setPosition(toPositionServer);
toItem.setPosition(fromPositionServer);
//updating Shoppinglist Item locally
viewModel.updateItem(fromItem);
viewModel.updateItem(toItem);
}
});
}
}}
and my Adapter class:
public class ShoppinglistAdapter extends ListAdapter<Shoppinglist, ShoppinglistAdapter.NoteHolder> implements ItemMoveCallback.ItemTouchHelperContract {
public Integer ressourceType;
private onPositionChanged onPositionChanged;
private ArrayList<Shoppinglist> globalItemList = new ArrayList<Shoppinglist>();
public ShoppinglistAdapter() {
super(DIFF_CALLBACK);
Integer valueOf = Integer.valueOf(0);
this.ressourceType = valueOf;
}
private static final DiffUtil.ItemCallback<Shoppinglist> DIFF_CALLBACK = new DiffUtil.ItemCallback<Shoppinglist>() {
#Override
public boolean areItemsTheSame(Shoppinglist oldItem, Shoppinglist newItem) {
return oldItem.getSqlid() == newItem.getSqlid();
}
#Override
public boolean areContentsTheSame(Shoppinglist oldItem, Shoppinglist newItem) {
return oldItem.getTitle().equals(newItem.getTitle());
}
};
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.shoppinglist_item, parent, false);
return new NoteHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull NoteHolder holder, int position) {
Shoppinglist currentItem = getItem(position);
holder.setIsRecyclable(false);
holder.tv.setText(currentItem.getTitle());
...
}
public Shoppinglist getNoteAt(int position) {
return getItem(position);
}
public class NoteHolder extends RecyclerView.ViewHolder {
private TextView tv;
public NoteHolder(View itemView) {
super(itemView);
tv= itemView.findViewById(R.id.tv);
globalItemList .add(currentNote);
}
}
public interface onPositionChanged {
void onPositionChanged(Shoppinglist fromItem, Shoppinglist toItem, int fromPosition, int toPosition);
}
public void setOnPositionChanged(ShoppinglistAdapter.onPositionChanged listener) {
this.onPositionChanged = listener;
}
#Override
public void onRowMoved(int fromPosition, int toPosition) {
//send switched Items to Fragment
onPositionChanged.onPositionChanged(globalItemList.get(fromPosition), globalItemList.get(toPosition), fromPosition, toPosition);
//switch Items inside of the global Item List
Collections.swap(globalItemList, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onRowSelected(NoteHolder myViewHolder) {}
#Override
public void onRowClear(NoteHolder myViewHolder) {}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
}
The problem is that you should swap items in ListAdapter.mDiffer which holds the current showing list. So, globalItemList in your code is unused. Replace onRowMoved of your adapter with the following one:
#Override
public void onRowMoved(int fromPosition, int toPosition) {
ArrayList<Shoppinglist> list = new ArrayList(getCurrentList());
Collections.swap(list, fromPosition, toPosition);
submitList(list);
}
how can i filter Recycler View using SearchView
i try all the video tuturial but all of them get thier item Recycler View from a list
but i get my item from db and dont know how should i do this
this is my adapter Code
public class AthleteAdapter extends RecyclerView.Adapter<AthleteAdapter.AthleteHolder> {
private List<Athlete> athletes = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public AthleteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.athlete_item, parent, false);
return new AthleteHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull AthleteHolder holder, int position) {
Athlete currnetAthlete = athletes.get(position);
holder.textViewName.setText(currnetAthlete.getAthlete_name());
holder.textViewLastname.setText(currnetAthlete.getAthlete_lastname());
holder.textView_phonenumber.setText(currnetAthlete.getAthlete_phonenumber());
holder.textViewTime1.setText(String.valueOf(currnetAthlete.getSign_in_time()));
holder.textViewTime2.setText(String.valueOf(currnetAthlete.getCheck_tution_time()));
}
public void setAthletes(List<Athlete> athletes) {
this.athletes = athletes;
notifyDataSetChanged();
}
public Athlete getposition(int position) {
return athletes.get(position);
}
#Override
public int getItemCount() {
return athletes.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public interface OnItemClickListener {
void onItemClick(Athlete athlete);
}
class AthleteHolder extends RecyclerView.ViewHolder {
private TextView textViewName, textViewLastname, textView_phonenumber, textViewTime1, textViewTime2;
public AthleteHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name_main);
textViewLastname = itemView.findViewById(R.id.lastname_main);
textView_phonenumber = itemView.findViewById(R.id.textView_number);
textViewTime1 = itemView.findViewById(R.id.time1);
textViewTime2 = itemView.findViewById(R.id.time2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(athletes.get(position));
}
}
});
}
}
}
Step 1 : Get all data from db and give that list to Adapter
usersList = db.getAll();
adapter = new dataAdapter(getApplicationContext(), usersList);
adapter.setdatainterfacemethod(this);
Step 2 : get Text from Searchview
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(s.toString());
}
return false;
}
});
Step 3 : compare searchview text and list text if exits then give list to adapter
public void filter(String text) {
List<Users> name = new ArrayList<>();
for (Users u : usersList) {
if (u.getNAME().toLowerCase().contains(text.toLowerCase())) {
name.add(u);
}
}
adapter.filterlist(name);
}
Step 4 :- change list and notify adapter (in adapter class)
public void filterlist(List<Users> name) {
this.usersList = name;
notifyDataSetChanged();
}
--------------------- Adapter class -----------------
public class dataAdapter extends RecyclerView.Adapter<dataAdapter.viewholder> {
public List<Users> usersList;
Context context;
dataInterface dataInterface;
public dataAdapter(Context context, List<Users> usersList) {
this.usersList = usersList;
this.context = context;
}
public void setdatainterfacemethod(dataInterface dataInterface) {
this.dataInterface = dataInterface;
}
#NonNull
#Override
public viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.include_recycle_demo, viewGroup, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final viewholder viewholder, final int i) {
}
#Override
public int getItemCount() {
return usersList.size();
}
public void filterlist(List<Users> name) {
this.usersList = name;
notifyDataSetChanged();
}
public class viewholder extends RecyclerView.ViewHolder {
public viewholder(#NonNull View itemView) {
super(itemView);
}
}
}
I am trying to implement simple recycler view in my Activity based on the following tutorial from official AndroidAnnotations site: adapter link
However when I finish all the steps, and I try to implement #ItemClick method, it gives me the following error:
Error:(84, 36) error: incompatible types: RecyclerView cannot be converted to AdapterView
with the following code highlighted under my generated activity code:
...((AdapterView<?> ) this.miestnostiList).setOnItemClickListener(new OnItemClickListener() {...
As per guide, I have created the following base classes:
public abstract class RecyclerViewAdapterBase<T, V extends View> extends RecyclerView.Adapter<ViewWrapper<V>> {
protected List<T> items = new ArrayList<T>();
#Override
public int getItemCount() {
return items.size();
}
#Override
public final ViewWrapper<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewWrapper<V>(onCreateItemView(parent, viewType));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
}
public class ViewWrapper<V extends View> extends RecyclerView.ViewHolder {
private V view;
public ViewWrapper(V itemView) {
super(itemView);
view = itemView;
}
public V getView() {
return view;
}
}
Then I created my row view item as following:
#EViewGroup(R.layout.activity_list_miestnosti_row)
public class MiestnostItemView extends LinearLayout{
#ViewById(R.id.txt_miestnost_row_nazov)
TextView nazov;
public MiestnostItemView(Context context) {
super(context);
}
public void bind(Miestnost miestnost){
nazov.setText(miestnost.getNazov());
}
}
and finally my adapter class:
public class ListMiestnostiAdapter extends RecyclerViewAdapterBase<Miestnost, MiestnostItemView> {
#RootContext
Context context;
#Override
protected MiestnostItemView onCreateItemView(ViewGroup parent, int viewType) {
return MiestnostItemView_.build(context);
}
#Override
public void onBindViewHolder(ViewWrapper<MiestnostItemView> holder, int position) {
MiestnostItemView view = holder.getView();
Miestnost miestnost = items.get(position);
view.bind(miestnost);
}
}
Under my Activity I initialize my adapter in #AfterViews section:
#ViewById
RecyclerView miestnostiList;
ListMiestnostiAdapter adapter;
#AfterViews
void bindAdapter() {
GetData();//fetch data
adapter = new ListMiestnostiAdapter();
adapter.addData(miestnosti);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
miestnostiList.setLayoutManager(layoutManager);
miestnostiList.setItemAnimator(new DefaultItemAnimator());
miestnostiList.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
miestnostiList.setAdapter(adapter);
}
Here is my #ItemClick method:
#ItemClick
void miestnostiListItemClicked(Miestnost miestnost){
Log.i("", "iteClicked: ");
}
What am I missing here?
I think #ItemClick is not available with RecyclerView. You can proceed in two ways:
1- Changing your RecyclerViewAdapterBase adding onClick support, then overriding that method into child adapter like so:
public abstract class RecyclerViewAdapterBase<T, V extends View & ViewWrapper.Binder<T>> extends RecyclerView.Adapter<ViewWrapper<T, V>> {
protected List<T> mItems = new ArrayList<T>();
#Override
public final ViewWrapper<T, V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewWrapper<T, V>(onCreateItemView(parent, viewType));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
#Override
public final void onBindViewHolder(ViewWrapper<T, V> viewHolder, int position) {
V view = viewHolder.getView();
T data = mItems.get(position);
/*************************************************************/
* AT THIS POINT IT TRY TO SET A CLICK LISTENER */
/*************************************************************/
setOnClickListener(view, data);
view.bind(data);
}
#Override
public int getItemCount() {
return null == mItems ? 0 : mItems.size();
}
public void add(T item) {
mItems.add(item);
notifyDataSetChanged();
}
public void addAll(Collection<T> collection) {
mItems.addAll(collection);
notifyDataSetChanged();
}
public void clear() {
mItems.clear();
}
/**
* override this into child adapter to manage click event
*/
public void setOnClickListener(View v, T item) {}
}
This is the child adapter
#EBean
public class ChildAdapter extends RecyclerViewAdapterBase<Child, ChildView> {
#RootContext
Context ctx;
#Bean(ChildFinder.class)
IChildFinder finder;
#Bean
OttoBus mOttoBus;
/**
* get data by finder
*/
public void initAdapter() {
mItems = finder.findAll();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
protected ChildView onCreateItemView(ViewGroup parent, int viewType) {
return ChildView_.build(ctx);
}
#Override
public void setOnClickListener(View v, final Child item) {
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOttoBus.post(new RequestChildEvent(item));
}
});
}
}
2- Otherwise if you are using custom views you can follow an event driven approach binding you click directly on the view (for example on the root view of your custom view) and then sending an event to the component that must react to the click
I am trying to use a RecyclerView with a vertical LinearLayoutManager in order to display a list items. This list can contain several different item types (differents layouts), and it can be reordered by the user using drag and drop.
For the item types, as documented in Android documentation, I have overridden the getItemType method in order to handle different types of views in the recycler and handle it in the onCreateViewHolder and onBindViewHolder. This works like a charm.
For the drag and drop reorder, I have used a ItemTouchHelper.Callback (inspired by this sample project). This also works well.
The problem happen when I try to use different items types AND the drag and drop behaviour. As long as the drag occurs between items of the same type, this works well, but when i'm draggin a view of type A over a view of type B, the drag stop and the view returned to it's original position.
Here is my code:
MyFragment.java
public class MyFragment extends Fragment implements MyAdapter.Listener {
private MyViewModel mViewModel;
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private ItemTouchHelper mItemTouchHelper;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment, container, false);
mRecyclerView = root.findViewById(R.id.recyclerView);
mAdapter = new MyAdapter(this);
mRecyclerView.setAdapter(mAdapter);
mItemTouchHelper = new ItemTouchHelper(new MyDragHelperCallback(mAdapter));
mItemTouchHelper.attachToRecyclerView(mRecyclerView);
mViewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
mViewModel.addObserver(this, new Observer<List<Item>>() {
#Override
public void onChanged(#Nullable List<Item> items) {
mAdapter.updateList(items);
}
});
mAdapter.updateList(mViewModel.getList());
return root;
}
#Override
public void onStartDragRequest(#NonNull RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
}
MyDragHelperCallback.java
public class MyDragHelperCallback extends ItemTouchHelper.Callback {
private static final int DRAG_MOVEMENT_FLAGS = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
#NonNull
private MyDragListener mListener;
public MyDragHelperCallback(#NonNull MyDragListener listener) {
mListener = listener;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return false;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
if (!(recyclerView.getLayoutManager() instanceof LinearLayoutManager)) {
throw new IllegalArgumentException("Should only be used with a LinearLayoutManager");
}
return makeMovementFlags(DRAG_MOVEMENT_FLAGS, 0);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
mListener.onItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// Nothing to do
}
}
MyDragListener.java
public interface MyDragListener {
void onItemMoved(int from, int to);
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements MyDragListener {
#Nullable
private List<Item> mList;
public void updateList(#Nullable List<Item> list) {
mList = list;
notifyDataSetChanged();
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new MyHolderBis(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bis, parent, false));
}
return new MyHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(final MyHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
mListener.onStartDragRequest(holder);
return true;
}
});
// bind views to data
}
#Override
public int getItemCount() {
return mList != null ? mList.size() : 0;
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getType();
}
#Override
public void onItemMoved(int from, int to) {
notifyItemMoved(from, to);
}
}
Is there something I missing ?
Or is this simply to possible to achieve ?
Thanks for all your answers !
I have a RecyclerView with a custom listener that I want to implement in my main activity so that it gets notified when the RecyclerView item gets clicked.
However, I'm not sure where to put setMyAdapterListener in the adapter. Where would I put it?
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Data> data;
private MyAdapterListener myAdapterListener;
public MyAdapter(Context context, List<Object> data) {
this.context = context;
this.data = data;
}
public interface MyAdapterListener {
void onContainerClick();
}
public void setMyAdapterListener(MyAdapterListener myAdapterListener) {
this.myAdapterListener = myAdapterListener;
}
public class ViewHolderItem extends RecyclerView.ViewHolder implements View.OnClickListener {
public LinearLayout container;
public ImageView poster;
public ViewHolderItem(View v) {
super(v);
container = (LinearLayout) v.findViewById(R.id.container);
poster = (ImageView) v.findViewById(R.id.poster);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.container) {
if (myAdapterListener != null) {
myAdapterListener.onContainerClick();
}
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v2 = inflater.inflate(R.layout.item_layout, parent, false);
viewHolder = new ViewHolderItem(v2);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Data item = (Data) data.get(position);
holder.poster.setImageDrawable(someDrawable);
}
#Override
public int getItemCount() {
return data.size();
}
}
Remove the setMyAdapter() just pass the arguments you currently have in your setMyAdapterListener as part of your recyclerview's adapter contructor, see below:
public MyAdapter(Context context, List<Object> data, MyAdapterListener myAdapterListener) {
this.context = context;
this.data = data;
this.myAdapterListener = myAdapterListener;
}
//On your activity you have to implement the methods of your interface.
As #ScottS Said you dont need setMyAdapter() method, just pass the onclick listener Interface class as a argument to your adapter constructor then implement the interface methods in activity Class .. code is shown below.
public MyAdapter(Context context, List<Object> data) {
this.context = context;
this.data = data;
this.myAdapterListener = myAdapterListener;
}
public interface MyAdapterListener {
void onContainerClick(); // please provide 2 parameter that will help you more for manipulation like shown below
/// void onContainerClick(View view, int position);
}
}
public class ViewHolderItem extends RecyclerView.ViewHolder implements View.OnClickListener {
public LinearLayout container;
public ImageView poster;
public ViewHolderItem(View v) {
super(v);
container = (LinearLayout) v.findViewById(R.id.container);
poster = (ImageView) v.findViewById(R.id.poster);
container =setOnClickListener(this); /// this line must include
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.container) {
if (myAdapterListener != null) {
myAdapterListener.onContainerClick();
// myAdapterListener.onContainerClick(v,getAdapterPosition());
}
}
}
}
Then you can handle the events in your Activity or wherever your RecyclerView is being used:
mAdapter = new MyAdapter(getApplicationContext() , data, new MyAdapter.MyAdapterListener() {
#Override
public void onContainerClick(View v, int position) {
Log.d(TAG, "iconTextViewOnClick at position "+position);
}
});
mRecycler.setAdapter(mAdapter);