Recyclerview not refreshing after removing an item - android

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

Related

How to save user inputs from dialog to a RecyclerView as an item?

I Have implemented an Add/Edit dialog for recyclerview(first recyclerview) item, which will ask the user for inputs.
Basically what I need to know is to take user inputs from the dialog and save them as items to another RecyclerView(RecyclerView two), which is within a fragment?
A code or a sample will even be more than welcome. Following is the code so far in the adapter class for my attempt.
public class ContReceiptsAdapter extends RecyclerView.Adapter<ContReceiptsAdapter.ReceiptsViewHolder> {
private ArrayList<Contract> contracts;
Context mContext;
String inPending;
//for the details dialog
EditText et_number, contract_id_val, product_type_val, mobile_number_ADialog;
// ImageView btn_add_item;
//--to set to add item dialog
public TextView contract_number, vehicle_number, contract_number_ADialog, vehicle_number_ADialog ;
CheckBox checkbox_pending;
private ItemOnClickListener mListener;
public interface ItemOnClickListener {
void onItemClicked(View view,int index);
void onItemDelete(int index);
void onItemAdd(int index);
}
public void setmListener(ItemOnClickListener listener) {
this.mListener = listener;
}
public ContReceiptsAdapter(Context context, ArrayList<Contract> contractList) {
contracts = contractList;
mContext = context;
}
public class ReceiptsViewHolder extends RecyclerView.ViewHolder {
TextView tv_contract, tvVehicleN, tvContractType;
ImageView btn_add_item;
LinearLayout detailsLayout;
public ReceiptsViewHolder(#NonNull final View itemView) {
super(itemView);
detailsLayout = itemView.findViewById(R.id.add_details_item_id);
tv_contract = itemView.findViewById(R.id.tv_contract);
tvVehicleN = itemView.findViewById(R.id.tvVehicleN);
tvContractType = itemView.findViewById(R.id.tvContractType);
btn_add_item = itemView.findViewById(R.id.btn_add_item);
}
}
#NonNull
#Override
public ContReceiptsAdapter.ReceiptsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.receipt_tobe_added_rv_item, viewGroup, false);
final ReceiptsViewHolder receiptsViewHolder = new ReceiptsViewHolder(view);
//dialog ini
// ShowDetails();
final Dialog detailedDialog = new Dialog(this.mContext);
detailedDialog.setContentView(R.layout.fragment_details);
receiptsViewHolder.detailsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//click view dto show the detaileds view of the list item
contract_number = detailedDialog.findViewById(R.id.contract_id_val);
vehicle_number = detailedDialog.findViewById(R.id.vehicle_num_val);
contract_number.setText(contracts.get(receiptsViewHolder.getAdapterPosition()).getContractNumber());
vehicle_number.setText(contracts.get(receiptsViewHolder.getAdapterPosition()).getVehicleNumber());
detailedDialog.show();
detailedDialog.setCancelable(true);
}
});
return receiptsViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ContReceiptsAdapter.ReceiptsViewHolder viewHolder, int i) {
viewHolder.itemView.setTag(contracts.get(i));
viewHolder.tv_contract.setText(contracts.get(i).getContractNumber());
viewHolder.tvVehicleN.setText(contracts.get(i).getVehicleNumber());
viewHolder.tvContractType.setText(contracts.get(i).getContractType());
final Dialog AddItemDialog = new Dialog(mContext);
AddItemDialog.setContentView(R.layout.fragment_add_receipt);
viewHolder.btn_add_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ShowDetails();
contract_number_ADialog = AddItemDialog.findViewById(R.id.contract_id_val_add);
contract_number_ADialog.setText(contracts.get(viewHolder.getAdapterPosition()).getContractNumber());
vehicle_number_ADialog = AddItemDialog.findViewById(R.id.product_type_val_add);
vehicle_number_ADialog.setText(contracts.get(viewHolder.getAdapterPosition()).getVehicleNumber());
//this mobile number is an iput taken from user
mobile_number_ADialog = AddItemDialog.findViewById(R.id.et_number_add);
mobile_number_ADialog.setText(contracts.get(viewHolder.getAdapterPosition()).getMobileNumber());
//this checkbox value is also taken from user
checkbox_pending = AddItemDialog.findViewById(R.id.checkbox_pending_add);
checkbox_pending.setChecked(Boolean.parseBoolean(contracts.get(viewHolder.getAdapterPosition()).getPendingState()));
Button btn_cancel_receipt = AddItemDialog.findViewById(R.id.btn_cancel_receipt);
Button btn_add_receipt =AddItemDialog.findViewById(R.id.btn_add_receipt);
AddItemDialog.show();
AddItemDialog.setCancelable(true);
btn_cancel_receipt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this will close/cancel the user input dialog
AddItemDialog.dismiss();
}
});
btn_add_receipt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this is where i will get the inputs from edit/input dialog
//and try to pass those values to the second recycleview which will be added as an item
//add item to rv2
}
});
}
});
}
#Override
public int getItemCount() {
return contracts.size();
}
private void addAnItem() {
contract_number_ADialog.setText(contracts.get(viewHolder.getAdapterPosition()).getContractNumber());
}
btn_add_receipt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a Contract object, since list is of Contract type
// then add the user input to contract model, either through constructor or setter
// adn finally pass to this method
addItem(Contract contract);
}
});
}
private void addItem(Contract contract) {
contracts.add(Contract contract);
notifyDataSetChanged;
}
All codes are inside adapter

Recyclerview single item selection not working correctly

I've implemented a recyclerview with staggered gridLayout containing about 31 items in the arrayList, recyclerview is working correctly, but I faced issue relating to single item selection.
When I select the value till "26" as shown in figure, its working fine
But, when I select the value after "26", the values from top most item are also selected, as shown in this next figure.
I require to only select one item at a time.
I've implemented the following code in my adapter class
public class DialogAdapter extends
RecyclerView.Adapter<DialogAdapter.DialogHolder>
{
// components
public Context context;
public ArrayList<AlertDialogModel> dialogArrayList = new
ArrayList<AlertDialogModel>();
private final ArrayList<Integer> selected = new ArrayList<>();
private int lastCheckedPosition = -1;
public Interface interface;
// parameterized constructor
public DialogAdapter(Context context, ArrayList<AlertDialogModel>
dialogArrayList,Interface interface)
{
this.context = context;
this.dialogArrayList = dialogArrayList;
this.interface = interface;
}
#NonNull
#Override
public DialogHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_cardview,parent,false);
DialogHolder dialogHolder = new DialogHolder(view);
return dialogHolder;
}
#Override
public void onBindViewHolder(#NonNull final DialogHolder holder, final int position)
{
final AlertDialogModel alertDialogModel = dialogArrayList.get(position);
holder.textView.setText(alertDialogModel.getDisplayValue());
if(lastCheckedPosition == position)
{
holder.textView.setTextColor(context.getResources().getColor(R.color.white));
holder.textView.setBackground(context.getResources().getDrawable(R.drawable.circular_shape_selection));
}
else
{
}
holder.textView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
lastCheckedPosition = position;
notifyDataSetChanged();
holder.textView.setTextColor(context.getResources().getColor(R.color.white));
holder.textView.setBackground(context.getResources().getDrawable(R.drawable.circular_shape_selection));
interface.getSelectedValue(alertDialogModel.getDisplayValue());
}
});
}
#Override
public int getItemCount()
{
return dialogArrayList.size();
}
public static class DialogHolder extends RecyclerView.ViewHolder
{
public TextView textView;
public DialogHolder(View itemView)
{
super(itemView);
textView = (TextView)itemView.findViewById(R.id.textView);
}
}
}
Can anyone relate my code and identify the issue ?
holder.textView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
lastCheckedPosition = position;
notifyDataSetChanged();
holder.textView.setTextColor(context.getResources().getColor(R.color.white));
holder.textView.setBackground(context.getResources().getDrawable(R.drawable.circular_shape_selection));
interface.getSelectedValue(alertDialogModel.getDisplayValue());
//below line is important to remove previous selected position from the variable
lastCheckedPosition = -1;
}
});
you should put the text view to the original state:
if(lastCheckedPosition == position)
{
holder.textView.setTextColor(context.getResources().getColor(R.color.white));
holder.textView.setBackground(context.getResources().getDrawable(R.drawable.circular_shape_selection));
}
else
{
holder.textView.setTextColor(context.getResources().getColor(R.color.transparent));
holder.textView.setBackground(null));
}

passing values from recycler adapter to fragment in 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
}

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

how to call startActivity in RecyclerView Adapter (DataBinding)

My RecyclerView(rvPredictionIndex) item includes ImageView, EditText and Button, when Button is clicked the Text inside EditText will be uploaded on server and when ImageView is clicked, the New Activity will be called and the position of that Item will be passed to new activity using Intent().
I am using DataBinding so View() is not used here (or any other way of using View() than i don't know).
Here is RecyclerView Adapter code....
public class PredictionItemAdapter extends RecyclerView.Adapter<PredictionItemAdapter.MyViewHolder> {
private List<PredictionItems> mPredictionItemsList;
private Context mContext;
private int predictionId;
private String etAnswer;
public class MyViewHolder extends RecyclerView.ViewHolder {
// ImageView ivPredictionImage;
// CustomTextView txtPredictionQuestion;
PredictionItemBinding predictionItemBinding;
public MyViewHolder(PredictionItemBinding predictionItemBinding) {
super(predictionItemBinding.getRoot());
this.predictionItemBinding = predictionItemBinding;
// ivPredictionImage = (ImageView) itemView.findViewById(R.id.ivPredictionImage);
// txtPredictionQuestion = (CustomTextView) itemView.findViewById(R.id.txtPredictionQuestion);
}
}
public PredictionItemAdapter(Context context, List<PredictionItems> mPredictionItemsList) {
this.mPredictionItemsList = mPredictionItemsList;
this.mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prediction_item, parent, false);
// return new MyViewHolder(view);
PredictionItemBinding predictionItemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
R.layout.prediction_item, parent, false);
return new MyViewHolder(predictionItemBinding);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
// PredictionItems predictionItems = mPredictionItemsList.get(position);
// Picasso.with(mContext).load(predictionItems.getImage()).into(holder.ivPredictionImage);
// holder.txtPredictionQuestion.setText(predictionItems.getQuestion());
final PredictionItems predictionItems = mPredictionItemsList.get(position);
PredictionViewModel predictionViewModel = new PredictionViewModel(predictionItems);
predictionViewModel.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
#Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (propertyId == 1) {
etAnswer = holder.predictionItemBinding.editText.getText().toString();
predictionId = mPredictionItemsList.get(position).getId();
if (etAnswer.equals("")) {
Utility.showToastShort(mContext, "Please input answer");
} else {
callUpdatePredictionAnswerApi(predictionId, etAnswer);
// Toast.makeText(mContext, "submjit of " + holder.getAdapterPosition), Toast.LENGTH_SHORT).show();
}
}
else if (propertyId == 2){
//Here i want to start activity and pass data with intent
}
}
});
holder.predictionItemBinding.setPredictionVM(predictionViewModel);
}
#Override
public int getItemCount() {
return mPredictionItemsList.size();
}
}
I have already opened new activity on ItemClick of recyclerView but when i tried to click the EditText for input something, it will redirect me to the new activity, so that's why i want to start new activity on ImageView click..
here is my RecyclerViewItem Click...
private void rvPredictionIndexClick() {
rvPredictionIndex.addOnItemTouchListener(new RecyclerTouchListener(mContext, rvPredictionIndex, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
String preId = mPredictionItemsList.get(position).getId().toString();
Intent i = new Intent(mContext, PredictionInfoActivity.class);
String posi = ((String.valueOf(position)));
i.putExtra("predictionId", posi);
startActivity(i);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
Create Class DataBindingAdapter
and paste
#BindingAdapter("android:onClick")
public static void setOnClickListener(View view, final Runnable runnable) {
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runnable.run();
}
});
}
than go to your ViewModel class
and paste
public void onSubmitClicked() {
Log.e("onButtonSubmit", "onButtonSubmit");
notifyPropertyChanged(1);
}
public void onImageClicked() {
Log.e("onImageClicked", "onImageClicked");
notifyPropertyChanged(2);
}
than go to your item.xml file and call
android:onClick="#{predictionVM::onSubmitClicked}"
in your Button,
and
android:onClick="#{predictionVM.onImageClicked}
in your imaggView,
than go to your ItemAdapterClass
and inside onCreateViewHolder
predictionViewModel.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
#Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (propertyId == 1) {
//do your stuff
}
else if (propertyId == 2) {
// do your stuff
}
The most elegant and frankly adequate solution would be not to do anything inside adapter!
I wrote an article about adapters, have a look RecyclerView Adapters
Straightforward: add a callback to your adapter and perform everything inside calling sight (fragment etc)

Categories

Resources