passing values from recycler adapter to fragment in android - android

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
}

Related

How to open an activity from a recyclerview item?

I am trying to open another activity from a RecyclerView. I'm not understanding how to use the sendMessage() method to start the new activity. I have used the method in with another button to open a new activity all I want to do is to open up a the same activity but just with a different activity.
I have tried pluggin the sendMessage() method into the listener. I have tried using an intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildRecyclerView();
}
public void buildRecyclerView(){
mRecyclerView = findViewById(R.id.rvGoals);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new RVAdapter(mGoal);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
mDrawerLayout = findViewById(R.id.nav_view);
mDrawerLayout.openDrawer(Gravity.START);
}
#Override
public void onAddClick(int position) {
sendMessage();
}
});
public void sendMessage(View view) {
Intent intent = new Intent(this,MainGoalInfo.class);
startActivityForResult(intent,1);
}
Recycler View adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.GoalViewHolder> {
private List<Goals> goalsRVA;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
void onAddClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public RVAdapter(List<Goals> goalsRVA){
this.goalsRVA=goalsRVA;
}
#Override
public int getItemCount(){
return goalsRVA.size();
}
#Override
public GoalViewHolder onCreateViewHolder(ViewGroup viewGroup,int i){
View v=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.goal_view,viewGroup,false);
GoalViewHolder gvh=new GoalViewHolder(v,mListener);
return gvh;
}
#Override
public void onBindViewHolder(GoalViewHolder goalViewHolder, int i){
goalViewHolder.goalDescriptionRV.setText(goalsRVA.get(i).getDescription());
goalViewHolder.goalDueDateRV.setText(goalsRVA.get(i).getGoalDate());
goalViewHolder.goalTitleRV.setText(goalsRVA.get(i).getGoal());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView){
super.onAttachedToRecyclerView(recyclerView);
}
public static class GoalViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView goalDescriptionRV;
TextView goalDueDateRV;
TextView goalTitleRV;
ImageView mAddSubGoal;
GoalViewHolder(View itemView, final OnItemClickListener listener){
super(itemView);
cv=itemView.findViewById(R.id.shit_view);
goalTitleRV=itemView.findViewById(R.id.title);
goalDueDateRV=itemView.findViewById(R.id.dueDate);
goalDescriptionRV=itemView.findViewById(R.id.description);
mAddSubGoal=itemView.findViewById(R.id.ADDSUBGOAL);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
mAddSubGoal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onAddClick(position);
}
}
}
});
}
}
}
You can perform the desired action inside setOnClickListener() method of your GoalViewHolder. You can initialize the adapter with the context from your activity:
mAdapter = new RVAdapter(mGoal, this);
Recycler View adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.GoalViewHolder> {
private Context mContext;
...
public RVAdapter(List<Goals> goalsRVA, Context mContext){
this.goalsRVA=goalsRVA;
this.mContext=mContext
}
And in your GoalViewHolder:
GoalViewHolder(View itemView, final OnItemClickListener listener){
...
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext,MainGoalInfo.class);
((Activity) mContext).startActivityForResult(intent,1);
...
}
});
...
}
You can do that from inside onbindViewHolder
Send the context at the adapter constructor

Recyclerview not refreshing after removing an item

My Recycler view is not updating after an item is removed.
This recyclerView is inside a fragment.
I have tried every method and nothing works.
Adapter declaration in fragment class
notificationsTabAdapter = new NotificationsTabAdapter(getContext(), R.id.notificationsRecyclerView,
notificationItemsList, cListner);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(notificationsTabAdapter);
RecyclerViewAdapter:
public class NotificationsTabAdapter extends RecyclerView.Adapter<NotificationsTabAdapter.NotificationItemHolder> {
Boolean debug = false;
public static final String NOTIFICATION_ADAPTER = "NotificationAdapter";
private ArrayList<NotificationItemm> notificationItems;
private int layoutResID;
private int notificationposition;
private Context myContext;
public onNotificationItemClickListner mListner;
public interface onNotificationItemClickListner {
void onNotificationItemDelete(int position);
}
public NotificationsTabAdapter(Context context, int resource, ArrayList<NotificationItemm> notificationList,
onNotificationItemClickListner listner) {
myContext = context;
layoutResID = resource;
notificationItems = notificationList;
notificationposition = 0;
this.mListner = listner;
}
#NonNull
#Override
public NotificationItemHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notifications_tab_item, viewGroup, false);
NotificationsTabAdapter.NotificationItemHolder evh = new NotificationsTabAdapter.NotificationItemHolder(view, mListner);
return evh;
}
#Override
public void onBindViewHolder(#NonNull final NotificationItemHolder notificationItemHolder, final int position) {
final NotificationItemm currentItem = notificationItems.get(position);
notificationItemHolder.mNotificationTextView.setText(currentItem.getNotification_name());
notificationItemHolder.mNotificationURL = currentItem.getNotification_link();
notificationItemHolder.mNotificationDate = currentItem.getNotification_date();
notificationItemHolder.mNotificationRT = currentItem.getNotification_rT();
notificationItemHolder.mNotificaionHolderLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
//to delete the notification
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteNotification(currentItem);
mListner.onNotificationItemDelete(position);
}
});
}
#Override
public int getItemCount() {
return notificationItems.size();
}
//Delete from View
public void deleteNotification(NotificationItemm todelete) {
int notificationPosition = notificationItems.indexOf(todelete);
notificationItems.remove(notificationPosition);
notifyItemRemoved(notificationPosition);
notifyItemChanged(notificationPosition);
notifyDataSetChanged();
notifyItemRemoved(notificationPosition);
notifyItemChanged(notificationPosition);
if (notificationItems.isEmpty()) {
}
}
/**
* VIEW HOLDER =================================================================================
**/
public class NotificationItemHolder extends RecyclerView.ViewHolder {
RelativeLayout mNotificaionHolderLayout;
RelativeLayout notificationParentRelative;
ImageView imageDelete;
TextView mNotificationTextView;
String mNotificationURL;
String mNotificationDate;
String mNotificationRT;
public NotificationItemHolder(#NonNull View itemView, onNotificationItemClickListner listner) {
super(itemView);
mNotificationTextView = itemView.findViewById(R.id.NotificationTextView);
mNotificaionHolderLayout = itemView.findViewById(R.id.notification__item_container);
imageDelete = itemView.findViewById(R.id.notification_delete_image);
notificationParentRelative = itemView.findViewById(R.id.rlNotificLayout);
mNotificationRT = null;
mNotificationURL = null;
mNotificationDate = null;
}
}
}
When I debug the project, I can see that the item is actually removing from the ArrayList.But not updating in recycled view.
After deletion, if the recyclerview is scrolled, the deleted item is removed from the recyclerview.But not without scrolling.
Try this.Hope will work for you.
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notificationItems.remove(position);
notifyDataSetChanged();
}
In your NotificationsTabAdapter make the following changes
NotificationsTabAdapterListener notificationsTabAdapterListener;
public interface NotificationsTabAdapterListener { // create an interface
void onItemsDeleted(int position); // create callback function
}
public NotificationsTabAdapter(Context context, int resource, ArrayList<NotificationItemm> notificationList,
NotificationsTabAdapterListener notificationsTabAdapterListener) {
myContext = context;
layoutResID = resource;
notificationItems = notificationList;
notificationposition = 0;
this.notificationsTabAdapterListener = notificationsTabAdapterListener;
}
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//perform normal remove operation here
notificationItems.remove(position);
notificationsTabAdapterListener.onItemsDeleted(position);
}
});
And Implement NotificationsTabAdapterListener in you fragment and in override method use the following code
#Override
public void onItemsDeleted(final int position) {
notificationsTabAdapter.notifyDataSetChanged();
recyclerView.post(new Runnable() {
#Override
public void run() {
recyclerView.smoothScrollToPosition(position);
}
});
}
Try this to your delete functionality
public void deleteNotification(NotificationItemm todelete) {
notificationItems.remove(todelete);
notifyDataSetChanged();
}
As workaround you can call a method in the FragmentClass, which loads the new list (with item removed) in your adapter. Call this method from your Adapter
public void MethodInFragmentClass(NotificationItemm todelete)
{
/*
... delete item
*/
notificationsTabAdapter = new NotificationsTabAdapter(getContext(), R.id.notificationsRecyclerView,
notificationDeletedItemsList, cListner);
recyclerView.setAdapter(notificationsTabAdapter);
}
Use a callback like this in your adapter :
private ICallback mICallback;
public interface ICallback {
void deleteItem(int position);
}
public SettingRecyclerViewAdapter(SettingMediator settingMediator, ICallback ICallback) {
mICallback = ICallback;
mSettingMediator = settingMediator;
}
And in your faragment notifydatasetchange and update recyclerview like this :
public class YourFragment implements SettingContract.View, SettingRecyclerViewAdapter.ICallback {
.
.
.
#Override
public void deleteItem(int position) {
//delete item from your list here
mSettingRecyclerViewAdapter = new SettingRecyclerViewAdapter(yourList, this);
mRecyclerView.setAdapter(mSettingRecyclerViewAdapter);
mSettingRecyclerViewAdapter.notifyDataSetChanged();
}
}
Try this:
notificationItemHolder.imageDelete.setTag(holder);
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotificationItemHolder viewholder = (NotificationItemHolder) v.getTag();
notificationItems.remove(viewholder.getAdapterPosition());
notifyDataSetChanged();
}
});
You have to parse the position which is getting from onclick listener in Adapter class to Interface method(onitemClicked())
Then, Implement the interface class to Fragment class and will remove the position which we have on Interface method using [ listname.remove(position)) ]
Eventually, update recyclerview UI using adaptername.notifyDataSetChanged();
Step 1 :create interface class
public interface RecyclerviewItemClickListener {
void onitemClicked(View v, int position);
}
Step 2: pass position to the interface method in adapter class
notificationItemHolder.imageDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteNotification(currentItem);
//use interface method & pass the position of the list to fragment for update UI .
recyclerviewItemClickListener.onitemClicked(v,position);
}
});
step 3 : implement the interface class & method in fragment
#Override
public void onitemClicked(View v, int position) {
Listname.remove(Listname.get(position));
RecyclerviewAdaptername.notifyDataSetChanged();
}

Access arraylist from a recycleradapter class

I want to access an ArrayList from a nonactivity class to a fragment.
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position)
{
holder.setIsRecyclable(false);
holder.itemid.setText(mDataset.get(position).getItem_id());
holder.itemname.setText(mDataset.get(position).getItem_name());
holder.qty.setText(mDataset.get(position).getQty());
int rt=Integer.parseInt(mDataset.get(position).getRate().substring(0,mDataset.get(position).getRate().length() - 3));
holder.rate.setText(formatter.format(rt)+".00");
ItemDetails listItem = filterList.get(position);
holder.itemname.setText(listItem.getItem_name());
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
holder.qty.setText(String.valueOf(++qt));
mDataset.get(position).setQty(String.valueOf(qt));
finalDataset.add(new ItemDetails(ItemFragment.getInstance().cat_id,String.valueOf(holder.itemid.getText()),String.valueOf(holder.itemname.getText()),String.valueOf(holder.rate.getText()),String.valueOf(holder.qty.getText())));
}
});
holder.minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(qt==0)
{
holder.qty.setText(String.valueOf(0));
}
else
{
holder.qty.setText(String.valueOf(--qt));
}
mDataset.get(position).setQty(String.valueOf(qt));
finalDataset.add(new ItemDetails(ItemFragment.getInstance().cat_id,String.valueOf(holder.itemid.getText()),String.valueOf(holder.itemname.getText()),String.valueOf(holder.rate.getText()),String.valueOf(holder.qty.getText())));
}
});
}
finalDataset is the mentioned ArrayList. I added the values to the ArrayList inside the onBindViewHolder method in recycleradapter class. And I want to access it in another fragment.
Create method to return List in adapter class,
public List<ItemDetails> getDataset() {
return finalDataset;
}
In fragment class access it using,
List<ItemDetails> finalDataset = adapter.getDataset();

How do I detect if a button from an activity is clicked while inside a RecyclerView adapter

I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}

Recyclerview touch events

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
}
});

Categories

Resources