This is the first time I am working with RecyclerView, I have made Adapter class with some static mock data.
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ViewHolder(View view){
super(view);
textView = (TextView)view.findViewById(R.id.MyTextView);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view1 = LayoutInflater.from(context).inflate(R.layout.item, parent ,false);
Toast.makeText(context, "############" +viewType, Toast.LENGTH_SHORT).show();
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(SubjectValues[position]);
}
#Override
public int getItemCount() {
return SubjectValues.length;
}
}
this is my Adapter clas now it's showing the mock data I want to achieve the click event.
In Adapter class, inside onBindViewHolder() method, you can register listener to the whole row as the following :
vh1.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "General click !", Toast.LENGTH_SHORT).show();
}
});
If you want to register listener to a specific view inside a row layout, you can do it as the following :
vh1.getButton().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "Button is clicked ! ", Toast.LENGTH_SHORT).show();
}
});
The whole source code for the adapter class :
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
}
}
private void configureViewHolder1(ViewHolder1 vh1, int position) {
User user = (User) items.get(position);
if (user != null) {
vh1.getLabel1().setText("Name: " + user.name);
vh1.getLabel2().setText("Hometown: " + user.hometown);
vh1.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "General click !", Toast.LENGTH_SHORT).show();
}
});
vh1.getButton().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(ComplexRecyclerViewAdapter.this, "Item no: "+ position, Toast.LENGTH_LONG).show;
Toast.makeText(v.getContext(), "Button is clicked ! ", Toast.LENGTH_SHORT).show();
}
});
}
}
ViewHolder1.java
public class ViewHolder1 extends RecyclerView.ViewHolder {
private TextView label1, label2;
private Button button;
public ViewHolder1(View v) {
super(v);
...
button = (Button) v.findViewById(R.id.button);
}
public Button getButton() {
return button;
}
public void setButton(Button button) {
this.button = button;
}
}
Inside your onBindViewHolder set OnClickListener
#Override
public void onBindViewHolder(final HomeListAdapter.MainViewHolder homeViewHolder, final int position) {
homeViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(this, "Item no: "+ position, LENGTH_SHORT).show;
}
});
}
Using this way will make items layout clickable not only a textview or button.
If perticularly you want to give action on click of button or textveiew then you can use reference of those components e.g.
holder.button.setOnClickListener(new OnClick..)......
To add a click event add the following into the onBindViewHolder method:
holder.textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int adapterPos = holder.getAdapterPosition();
if(adapterPos != RecyclerView.NO_POSITION) {
Toast.makeText(context, SubjectValues[adapterPos], Toast.LENGTH_SHORT).show();
}
}
});
That would add a click listener to the textView which shows a toast of the value.
Note: I have made assumptions on what your SubjectValues is, as not included in your question.
But the important things to observe here are:
holder.getAdapterPosition()
Check position (!= RecyclerView.NO_POSITION)
Set this in onBindViewHolder
I believe this is a fair summary of how to set a click listener within a recyclerview adapter.
add this class to your project
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}}
then in your RecyclerView use this
myRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
YourModel model = modelList.get(position);
}
}));
Add OnItemClickListener interface into your adapter.
OnItemClickListener mItemClickListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void setOnItemClickListener(
final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
Implements OnItemClickListener on ViewHolder like below.
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ViewHolder(View view){
super(view);
textView = (TextView)view.findViewById(R.id.MyTextView);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getAdapterPosition());
}
}
}
In your Activity or Fragment setOnItemClickListener on your adapter.
mAdapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// Do your stuff here when item clicked
}
});
Related
I'm facing the next problem.
I have a RecyclerView with the Adapter, the items, etc.
What I need is: Select an item in the recycler, change the color of that item, and then I have to disable the rest of the other items. It's like a RadioButton list.
I select one and disable the others. If I select again the same item, enable all the list.
I already have the onClick Button listener. I need to know if I have to reload again de list, If I have to loop and disable item by item, etc.
Thanks
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Human> humans;
private HumanClick selectedHuman;
#Inject
public MyAdapter() {
}
public void init(List<Human> humanList, SelectedHumanClick humanClick){
this.humans = humanList;
this.humanClick = humanClick;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_Human, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
final Human human = Humans.get(position);
holder.bind(Humans.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedHumanClick.onSelectedHumanClick(Human);
}
});
}
#Override
public int getItemCount() {
return humans != null ? Humans.size() : 0;
}
public final class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.text_view_human_name)
TextView textView;
#BindView(R.id.image_view_profile)
ImageView imageViewProf;
#BindView(R.id.image_view_radio_btn)
ImageView imageViewRB;
private boolean isChecked = false;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final Human Human) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
humanClick.onSelectedHumanClick(Human);
}
});
textView.setText(human.getName());
}
public void changeRBImage() {
if(!isChecked){
isChecked = true;
imageViewRB.setBackground(ContextCompat.getDrawable(imageViewRB.getContext(), R.drawable.selected));
}
else{
isChecked = false;
imageViewRB.setBackground(ContextCompat.getDrawable(imageViewRB.getContext(), R.drawable.not_selected));
}
}
}
My Recycler is defined inside a fragment here:
public class HumansFragment implenets HumanClick{
#BindView(R.id.recycler_humans)
RecyclerView humansRecyclerView;
#Inject
MyAdapter myAdapter;
.
.
.
public void loadHumans(List<Human> humans) {
myAdapter.init(Humans, this);
humansRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
humansRecyclerView.setAdapter(myAdapter);
}
#Override
public void humansClick(Human human) {
//TODO
}
}
I'm thinking in something like this, using setOnItemClickListener and check the position of the item clicked. The position is the index of the item clicked check the last event and new, if both are equal change color, if not dont do anything like disabling.
private ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textView = (TextView)view.findViewById(android.R.id.text1);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();
//go through each item if you have few items within recycler view
if(getLayoutPosition()==0){
//Do whatever you want here
}else if(getLayoutPosition()==1){
//Do whatever you want here
}else if(getLayoutPosition()==2){
}else if(getLayoutPosition()==3){
}else if(getLayoutPosition()==4){
}else if(getLayoutPosition()==5){
}
//or you can use For loop if you have long list of items. Use its length or size of the list as
for(int i = 0; i<exampleList.size(); i++){
}
}
}
Or something smaller
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, recyclerView ,new
RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
I've a recycler adapter where I've added setOnClickListener for items in adapter. Code is as given below:
#Override
public void onBindViewHolder(final FiltersAdapter.MyViewHolder holder, final int position) {
holder.mOrganizer.setText(filtersList.get(position));
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Log.e("message","ONclick FIlter");
if (holder.mOrganizerCheck.isChecked()){
holder.mOrganizerCheck.setChecked(false);
}else {
holder.mOrganizerCheck.setChecked(true);
int pos = holder.getAdapterPosition();
filtersList.get(pos);
/*Bundle bundle = new Bundle();
bundle.putInt(pos, );*/
Log.d(TAG, "onClick: " +filtersList);
Log.d(TAG, "onClick of position: " +pos);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
And here is fragment code which deals with getting values from adapter to fragment.
private void initView() {
mrvFilterBySender = (RecyclerView) mFilterView.findViewById(R.id.rvFilterBySender);
mFiltersAdapter = new FiltersAdapter(getActivity(), mListOrganizer);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mrvFilterBySender.setLayoutManager(mLayoutManager);
mrvFilterBySender.setAdapter(mFiltersAdapter);
mFiltersAdapter.notifyDataSetChanged();
mrvFilterBySender.setAdapter(mFiltersAdapter);
mrvFilterBySender.setRecyclerListener(new RecyclerView.RecyclerListener() {
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
holder.getAdapterPosition();
}
});
}
I'm trying to pass pos and value having that pos from adapter to fragment. But my code isn't working. How can I fix it?
make interface to handle click event into recyclerview ..
used below code for handling click event.
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner{
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
String data=mStringList.get(position); // if you pass object of class then create that class object.
holder.textView.setText(data);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
then after when you bind adapter into RecyclerView call below code..
mRvData.setLayoutManager(new LinearLayoutManager(this));
mRvData.setAdapter(recyclerViewAdpater);
recyclerViewAdpater.notifyDataSetChanged();
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
});
Create an interface in your adapter
public interface OnItemClickListener {
void onItemClicked(int position, Object object);
}
in your adapter call
Adapter adapter = new Adapter(context, list, new Adapter.OnItemClickListener() {
#Override
public void onItemClicked(int position, Object object) {
// Handle Object of list item here
}
});
on your adapter
private OnItemClickListener onItemClickListener; // Global scope
in constructor call:
this.onItemClickListener = onItemClickListener;
on your item clicked event :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClicked(position, _list.get(position));
}
});
Please use an interface like below, pass it in the adapter's constructor, and than use it in your activity / Fragment
public MyAdapter(Context context, List<Object> data, MyAdapterListener myAdapterListener) {
this.context = context;
this.data = data;
this.myAdapterListener = myAdapterListener;
}
public interface MyAdapterListener {
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(v,getAdapterPosition());
}
}
}
}
Use it like this in your fragment/Activity
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);
I thing this is work for you
Add in you adapter
public interface ClickEvent {
void clickEventItem(int position,String value);
}
ClickEvent clickevent;
public void setClickEvent(ClickEvent event) {
this.clickevent = event;
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickevent.clickEventItem(position, list.get(position));
}
});
in your fragment set interface
adapter.setClickEvent(your class context);
implement ClickEvent intereface and generate #Override method
#Override
public void clickEventItem(int position,String value) {
//write your code here
}
I am using Firebase UI FirebaseRecyclerAdapter to populate a RecyclerView. I managed to get click events from components of my item view (the title), but not for anywhere in the item view, which is what I need. I followed google sample.
In my Activity:
private void setRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.recycler_view_gigs);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new FirebaseRecyclerAdapter<Gig, GigViewHolder>(Gig.class,
R.layout.list_item_card,
GigViewHolder.class,
reference) {
#Override
protected void populateViewHolder(final GigViewHolder viewGig, Gig model, final int position) {
viewGig.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(Utils.TAG, "onItemClickGeneral: position " + position);
// this doesn't work
}
});
viewGig.bindToGig(model, new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(Utils.TAG, "onItemClickTitle: position " + position);
// this works
}
});
}
};
recyclerView.setAdapter(mAdapter);
}
and my ViewHolderClass:
public class GigViewHolder extends RecyclerView.ViewHolder {
ImageView ivIconArtist;
TextView tvArtist;
TextView tvVenue;
TextView tvDate;
public GigViewHolder(View view) {
super(view);
ivIconArtist = (ImageView) view.findViewById(R.id.iv_list_item_icon_artist);
tvArtist = (TextView) view.findViewById(R.id.tv_list_item_artist);
tvVenue = (TextView) view.findViewById(R.id.tv_list_item_venue);
tvDate = (TextView) view.findViewById(R.id.tv_list_item_date);
}
public void bindToGig(Gig gig, View.OnClickListener clickListener) {
tvArtist.setText(gig.getArtist());
tvVenue.setText(gig.getVenue());
tvDate.setText(gig.getDate());
tvArtist.setOnClickListener(clickListener);
}
}
I tried the custom onclicklistener + interface suggested in other answers, no luck either.
Implementing click and long click listener for entire row / items in FirebaseRecyclerViewAdapter.
I did this in this way.
First, define an interface in your ViewHolder class to send callbacks.
Inside its constructor, you can set click/long-click listener for entire row or a single componnent.
Then override onCreateViewHolder of FirebaseRecyclerAdapter where you will implement this interface.
IMPLEMENTATION
My FirebaseViewHolder class.
public class FirebaseViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mPostTitle;
public TextView mPostDesc;
public FirebaseViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.image_recyclerview);
mPostTitle = (TextView) itemView.findViewById(R.id.tv_title_recyclerview_item);
mPostDesc = (TextView) itemView.findViewById(R.id.tv_desc_recyclerview_item);
//listener set on ENTIRE ROW, you may set on individual components within a row.
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickListener.onItemClick(v, getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mClickListener.onItemLongClick(v, getAdapterPosition());
return true;
}
});
}
private FirebaseViewHolder.ClickListener mClickListener;
//Interface to send callbacks...
public interface ClickListener{
public void onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
public void setOnClickListener(FirebaseViewHolder.ClickListener clickListener){
mClickListener = clickListener;
}
}
Creating the FirebaseRecyclerAdapter.
FirebaseRecyclerAdapter<Post, FirebaseViewHolder> adapter = new FirebaseRecyclerAdapter<Post, FirebaseViewHolder>(
Post.class,
R.layout.recyclerview_list_item,
FirebaseViewHolder.class,
databaseReference
) {
#Override
protected void populateViewHolder(FirebaseViewHolder viewHolder, Post model, int position) {
Picasso.with(getActivity())
.load(model.image_url)
.into(viewHolder.mImageView);
Log.v(TAG, model.image_url);
//viewHolder.mImageView.setImageResource(R.mipmap.ic_launcher);
viewHolder.mPostTitle.setText(model.title);
viewHolder.mPostDesc.setText(model.desc);
}
#Override
public FirebaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
FirebaseViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new FirebaseViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemLongClick(View view, int position) {
Toast.makeText(getActivity(), "Item long clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
return viewHolder;
}
};
There are several answers to this question. One that worked for me was the answer provided by Frank van Puffelen how-to-implement-a-setonitemclicklistener-firebaserecyclerviewadapter
You need to change few things.
Before GigViewHolder constructor inside your public class GigViewHolder extends RecyclerView.ViewHolder define a global variable like this View itemView;
Inside GigViewHolder constructor, assign this variable the view passed as a parameter on your constructor like this this.itemView= view;
Then use this itemView in your populateViewHolder method as you had done as also shown
viewGig.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(Utils.TAG, "onItemClickGeneral: position " + position);
// This WORKS, write your TODO here
}
});
You can also explore other options on the following links:
RecyclerView onClick
I have recycler view with OnItemTouchListener and each row this recycler has a button with onclick event.
I want after click button event work but OnItemTouchListener work.
please help. my code.
public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerViewTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener=clickListener;
gestureDetector=new GestureDetector(new GestureDetector.SimpleOnGestureListener(){
#SuppressWarnings("deprecation")
#Override
public boolean onSingleTapUp(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child!=null && clickListener!=null){
clickListener.OnClick(child,recyclerView.getChildPosition(child));
}
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
//noinspection deprecation
clickListener.OnClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public static interface ClickListener {
void OnClick(View view,int position);
}
}
this code in viewholder
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
callbacks.removePosition(getAdapterPosition());
}
});
Sorry for my straightness, but first of all delete this code. Then you need to create your own RecyclerAdapter that will have such snippet of code:
View.OnClickListener clickListener;
public void setOnItemClickListener(View.OnClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (onClickListener != null) {
holder.itemView.setOnClickListener(clickListener);
}
}
Then somewhere where you work with RecyclerView (Activity, Fragment, custom View, custom Wrapper for View) you should do something like that:
List<SomeItem> someItems = getSomeItems();//Receive items for adapter from some place
MyRecyclerAdapter adapter = new MyRecyclerAdapter(someItems);
adapter.setOnItemClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = orderListView.getChildAdapterPosition(v);
SomeItem item = someItems.get(position);
Log.v("CLICKED", "Clicking on item(" + position + ", " + item + ")");
}
});
recyclerView.setAdapter(adapter);
Next to your question about clicking on buttons inside any item.
Define your own Holder that keeps references for View components inside you item:
public static class MyHolder extends RecyclerView.ViewHolder {
private final Button deleteButton;
public MyHolder(View itemView) {
super(itemView);
deleteButton = (Button) itemView.findViewById(R.id.delete_button);
}
public Button getDeleteButton() {
return deleteButton;
}
}
Then define your own inteface for define clicks on delete button. For example:
public interface OnDeleteButtonItemClickListener {
void onDeleteIsClick(View button, int position);
}
Then attach your interface to Adapter:
View.OnClickListener clickListener;
OnDeleteButtonItemClickListener deleteButtonListener;
public void setOnItemClickListener(View.OnClickListener clickListener) {
this.clickListener = clickListener;
}
public void setDeleteButtonListener(OnDeleteButtonItemClickListener deleteButtonListener) {
this.deleteButtonListener= deleteButtonListener;
}
#Override
public final void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (clickListener!= null) {
holder.itemView.setOnClickListener(clickListener);
}
if (deleteButtonListener!= null) {
MyHolder myHolder = (MyHolder) holder;
myHolder.getDeleteButton().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteButtonListener.onDeleteIsClick(v, position)
}
});;
}
}
And then update your place, where you work with RecyclerView:
List<SomeItem> someItems = getSomeItems();//Receive items for adapter from some place
MyRecyclerAdapter adapter = new MyRecyclerAdapter(someItems);
adapter.setOnItemClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = orderListView.getChildAdapterPosition(v);
SomeItem item = someItems.get(position);
Log.v("CLICKED", "Clicking on item(" + position + ", " + item + ")");
}
});
adapter.setDeleteButtonListener(new OnDeleteButtonItemClickListener {
#Override
public void onDeleteIsClick(View button, int position) {
SomeItem item = someItems.get(position);
Log.v("CLICKED", "Clicking on delete button of item(" + position + ", " + item + ")");
}
});
recyclerView.setAdapter(adapter);
I have list of data with CheckBox. I need to check or uncheck my Check Box from my RecyclerView. When I am trying this more than one check box is selected.
public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.MyStudentsViewHolder>{
private LayoutInflater inflater;
private Context contexts;
List<studinformation> data= Collections.emptyList();
public AttendanceAdapter(Context context,List<studinformation> data){
inflater=LayoutInflater.from(context);
this.data=data;
this.contexts=context;
}
#Override
public MyStudentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= inflater.inflate(R.layout.customrow_students,parent,false);
MyStudentsViewHolder holder=new MyStudentsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyStudentsViewHolder holder, int position) {
studinformation current=data.get(position);
holder.studentid.setText(current.studID);
holder.studentname.setText(current.studName);
holder.studentid.setSelected(true);
}
#Override
public int getItemCount() {
return data.size();
}
class MyStudentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CheckBox studentid;
TextView studentname;
public MyStudentsViewHolder(View itemView) {
super(itemView);
studentid= (CheckBox) itemView.findViewById(R.id.ChkSid);
studentname= (TextView) itemView.findViewById(R.id.textName);
studentid.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contexts, "Item Clicked At" + getPosition(), Toast.LENGTH_SHORT).show();
if(getPosition()==0) {
// Intent intent = new Intent(contexts, SubActivity.class);
// contexts.startActivity(intent);
}
}
}
}
RecyclerView will reuse the view.so when you return after scrolling it will reset the data it's happening because you are not setting your checkbox selected or not.
In your StudInformation model class create a property isSelected
public class StudInformation
{
private boolean isSelected=false;
public void setSelected(boolean param)
{
this.isSelected=param;
}
public boolean isSelected()
{
return this.isSelected;
}
}
Inside onClick
#Override
public void onClick(View v) {
data.get(getLayoutPosition()).setSelected(studentid.isChecked());
}
In onBindViewHolder
#Override
public void onBindViewHolder(MyStudentsViewHolder holder, int position) {
.....
studinformation current=data.get(position);
holder.studentid.setSelected(current.isSelected());
}
Cross reference link
you have to use setTag() method to get position of each checkbox.
Use this code instead of holder.studentid.setSelected(true); and remove studentid.setOnClickListener(this);
holder.studentid.setChecked(data.get(position).isSelected());
holder.studentid.setTag(data.get(position));
holder.studentid.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
String id = String.valueOf(cb.getTag());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + id, Toast.LENGTH_LONG).show();
}
});