I'm Using a RecyclerView that works well. Except that when I click on element 1 it returns element 3 when I scroll down. And when I scroll up and click on the element 4 it returns the element 3.
This is my adapter
public class StarRVAdapter extends RecyclerView.Adapter<StarRVViewHolder>{
private Context c;
private ArrayList<Questions> questionEntries;
Questions qe;
public StarRVAdapter(Context c, ArrayList<Questions> questionEntries,Questions qe) {
this.c = c;
this.qe = qe;
this.questionEntries = questionEntries;
}
#Override
public StarRVViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(c).inflate(R.layout.actu_list_item,parent,false);
return new StarRVViewHolder(v,c);
}
#Override
public void onBindViewHolder(StarRVViewHolder holder, int position) {
qe = (Questions)this.getItem(position);
holder.setDate(qe.getQuestion_date());
holder.setContent(qe.getQuestion_content());
holder.setImg(qe.getImgUrl());
holder.setTitle(qe.getQuestion_title());
holder.setAsker(qe.getQuestion_username());
holder.setIsRecyclable(true);
//this is My OnclickListener
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoToView();
}
});
}
#Override
public int getItemCount() {
return questionEntries.size();
}
public Object getItem(int position) {
return questionEntries.get(position);
}
private void GoToView() {
Intent intent = new Intent(c,QuestionView.class);
Bundle b = new Bundle();
intent.putExtra("QuestionRef",qe.getTag_id());
intent.putExtra("ContentRef",qe.getQuestion_content());
intent.putExtra("TitleRef",qe.getQuestion_title());
intent.putExtra("ImgRef",qe.getImgUrl());
intent.putExtra("UsernameRef",qe.getQuestion_username());
intent.putExtra("DateRef",qe.getQuestion_date());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(c,intent, b);
//This is returning another item
}
}
Please help me
You are working with the wrong Questions object here. Allocate it in your click itself.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoToView(holder.getAdapterPosition()); // passing position
}
});
Change the signature of GoToView accordingly:
private void GoToView(int position) {
Questions qe = (Questions)this.getItem(position);
// Cool stuff with qe
}
No need to keep it an instance variable
final Questions qe = (Questions)this.getItem(position);
holder.setDate(qe.getQuestion_date());
holder.setContent(qe.getQuestion_content());
holder.setImg(qe.getImgUrl());
holder.setTitle(qe.getQuestion_title());
holder.setAsker(qe.getQuestion_username());
holder.setIsRecyclable(true);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GoToView(qe);
}
});
and change your
private void GoToView(Questions qe) {
Intent intent = new Intent(c,QuestionView.class);
Bundle b = new Bundle();
intent.putExtra("QuestionRef",qe.getTag_id());
intent.putExtra("ContentRef",qe.getQuestion_content());
intent.putExtra("TitleRef",qe.getQuestion_title());
intent.putExtra("ImgRef",qe.getImgUrl());
intent.putExtra("UsernameRef",qe.getQuestion_username());
intent.putExtra("DateRef",qe.getQuestion_date());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(c,intent, b);
//This is returning another item
}
Related
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();
}
I'm using Viewpager for slider and initially Recyclerview... When I load image from Server to recycler it's done... Now what i want to do that when ever someone click on particular item, it should be opened in second activity in which ViewPager I use.. example: When I click first Image, it should open that image in viewPager(slider).... And Also when someone swipe on ViewPager's activity it should load more images....
Code is Below and don't know what to do next. Please Help me.
RecyclerView
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.myViewHolder> {
ArrayList<model> mdata;
Context context;
public RecyclerViewAdapter(){ }
public RecyclerViewAdapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item,viewGroup,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final myViewHolder holder, int i) {
Picasso.get().load(mdata.get(holder.getAdapterPosition()).getWallpaper()).into(holder.wallpaper);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("wallpaperUrl",mdata.get(holder.getAdapterPosition()).getWallpaper());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
ImageView wallpaper;
Button set;
public myViewHolder(#NonNull View itemView) {
super(itemView);
wallpaper = itemView.findViewById(R.id.wallpaper);
set = itemView.findViewById(R.id.set);
}
}
Second Activity which have ViewPager:
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn = findViewById(R.id.setWallpaper);
mdata = new ArrayList<model>();
viewPager = findViewById(R.id.viewPager);
Intent intent = getIntent();
Integer[] colors_temp ={getResources().getColor(R.color.color1),
getResources().getColor(R.color.color2),
getResources().getColor(R.color.color3),
getResources().getColor(R.color.color4),
} ;
colors = colors_temp;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffSet, int pixels) {
if (position < adapter.getCount() -1 && position <(colors.length) -1){
viewPager.setBackgroundColor(
(Integer) argbEvaluator.evaluate
(positionOffSet,
colors[position],
colors[position + 1]));
}else{
viewPager.setBackgroundColor(colors[colors.length - 1]);
}
}
#Override
public void onPageSelected(final int i) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadImage downloadImage = new DownloadImage();
Bitmap bitmap = null;
try{
bitmap =
downloadImage.execute(mdata.get(i).getWallpaper()).get();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(SecondActivity.this, "Something went
Wrong! ", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference().child("wallpapers");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
model data = dataSnapshot1.getValue(model.class);
mdata.add(data);
}
adapter = new Adapter(mdata,getApplicationContext());
viewPager.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SecondActivity.this, "Failed! "+databaseError,
Toast.LENGTH_SHORT).show();
}
});
}
MyAdapter:
public class Adapter extends PagerAdapter {
ArrayList<model> mdata;
Context context;
LayoutInflater inflater;
public Adapter(){
}
public Adapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#Override
public int getCount() {
return mdata.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view.equals(o);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.pager_item,container,false);
ImageView wallpaper;
Button btn;
wallpaper = view.findViewById(R.id.wallpaperImage);
Picasso.get().load(mdata.get(position).getWallpaper()).into(wallpaper);
container.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
If you are loading the images from the server, and each image has an id, pass the id into then intent. When you open up the view that needs the image that was clicked, make a service call to retrieve the image from the server using it's id.
In your enter code here, add setOnclickListener to holser.iytemView, then create an intent for navigating to the second activity, and add this code in onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: LoadingProfileActivity");
Intent intent = new Intent(getContext(), SecondActivity.class);
/*
Extras
*/
mainActivityContext.startActivity(intent);
}
});
If you want to send the image or id that contained in this row add intent.putExtra() after the intent is created.
Like if I want to display the image in second activity ill put in
Intent intent = new Intent(getContext(), SecondActivity.class);
intent.putExtra("image_url", imageResource);
In SecondActivity firsts get the imageresource from the intent
String imageResouce = getIntent.getStringExtra("image_url");
Then display the image in image view
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
}
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)
can anyone tell how to maintain the position of items in recyclerview when a search filter has been implemented?
well the scenario is that when I search for item D which is in the 4 position the intent activity that is for item D became item A intent which is not what i want.
What i want is if I search for item D the activity for item D remains the same.
this problem is giving me stress for 2 days now so if anyone can help i will really appreciate it.
Here is my code for my RecyclerView Adapter
public class dog_recylerAdapter extends RecyclerView.Adapter<dog_recylerAdapter.dogViewHolder> {
ArrayList<dog_counter> arrayList = new ArrayList<>();
Context dog_context;
public static int tag;
dog_recylerAdapter(ArrayList<dog_counter> arrayList, Context dog_context) {
this.arrayList = arrayList;
this.dog_context = dog_context;
}
#Override
public dogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.petbook_dog, parent, false);
return new dogViewHolder(view, dog_context, arrayList);
}
#Override
public void onBindViewHolder(dogViewHolder holder, int position) {
holder.dog.setImageResource(arrayList.get(position).getCount());
holder.dog_name.setText(arrayList.get(position).getName());
}
#Override
public int getItemCount() {
return arrayList.size();
}
#Override
public long getItemId(int position) {
return arrayList.get(position).getCount();
}
public static class dogViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageButton dog;
TextView dog_name;
ArrayList<dog_counter> arrayList;
Context dog_context;
public dogViewHolder(View itemView, Context dog_context, ArrayList<dog_counter> arrayList) {
super(itemView);
this.arrayList = arrayList;
this.dog_context = dog_context;
itemView.setOnClickListener(this);
dog = (ImageButton) itemView.findViewById(R.id.petdog_imag1);
dog_name = (TextView) itemView.findViewById(R.id.petdog_name1);
dog.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
arrayList=new ArrayList<>();
if(position==0) {
Intent intent = new Intent(this.dog_context, dog_alaskan_malamute.class);
this.dog_context.startActivity(intent);
}
else if(position==1) {
dog.setOnClickListener(this);
Intent intent = new Intent(this.dog_context, dog_beagle.class);
this.dog_context.startActivity(intent);
}
else if(position==2) {
Intent intent = new Intent(this.dog_context, dog_chow_chow.class);
this.dog_context.startActivity(intent);
}
else if(position==3) {
Intent intent = new Intent(this.dog_context, dog_duchshand.class);
this.dog_context.startActivity(intent);
}
}
}
public void setFilter(ArrayList<dog_counter> newList) {
arrayList=new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
You can add tag to your views which implement onClickListener and later get the tag and do whatever you want based on them.
for example :
#Override
public void onBindViewHolder(dogViewHolder holder, int position) {
holder.dog.setImageResource(arrayList.get(position).getCount());
holder.dog_name.setText(arrayList.get(position).getName());
holder.dog.setTag(arrayList.get(position));
}
and in your on click listener :
#Override
public void onClick(View v) {
//int position = getAdapterPosition();
dog_counter clickedItem=(dog_counter) v.getTag();
arrayList=new ArrayList<>();
// here do whatever you want with cliekdItem and not with the position
//////............
}