I am using RecyclerView in my application to create a forum for the users.
But I have problem with position of item! sometimes items will show in wrong positions! and some times items sow twice and some items doesn't show!
I have diffrent views in my recyclerView and because of that I used of multiView in it.
This is my recyclerView Adapter that I am using:
public class chatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final ArrayList<ChatModel> chatArray = new ArrayList<>();
private Context mContext;
FragmentForum fragmentForum;
public chatAdapter(ArrayList<ChatModel> chatArray, Context mContext, FragmentForum fragmentForum) {
this.chatArray.addAll(chatArray);
this.mContext = mContext;
this.fragmentForum = fragmentForum;
}
public static class ViewHolderNoFile extends RecyclerView.ViewHolder {
ImageView reply;
TextView qText;
TextView aText;
TextView aUserName;
TextView qUserName;
LinearLayout layoutAnswer;
public ViewHolderNoFile(View v) {
super(v);
reply = (ImageView) v.findViewById(R.id.imgReplay);
qText = (TextView) v.findViewById(R.id.txt_question);
aText = (TextView) v.findViewById(R.id.txt_answer);
aUserName = (TextView) v.findViewById(R.id.txt_a_user_name);
qUserName = (TextView) v.findViewById(R.id.txt_q_user_name);
layoutAnswer = (LinearLayout) v.findViewById(R.id.answer_box_item);
}
}
public static class ViewHolderQFile extends RecyclerView.ViewHolder {
ImageView qImage;
ImageView reply;
TextView qText;
TextView aText;
TextView aUserName;
TextView qUserName;
LinearLayout layoutAnswer;
public ViewHolderQFile(View v) {
super(v);
qImage = (ImageView) v.findViewById(R.id.img_question);
reply = (ImageView) v.findViewById(R.id.imgReplay);
qText = (TextView) v.findViewById(R.id.txt_question);
aText = (TextView) v.findViewById(R.id.txt_answer);
qUserName = (TextView) v.findViewById(R.id.txt_q_user_name);
aUserName = (TextView) v.findViewById(R.id.txt_a_user_name);
layoutAnswer = (LinearLayout) v.findViewById(R.id.answer_box_item);
}
}
public static class ViewHolderAFile extends RecyclerView.ViewHolder {
ImageView aImage;
ImageView reply;
TextView qText;
TextView aText;
TextView aUserName;
TextView qUserName;
LinearLayout layoutAnswer;
public ViewHolderAFile(View v) {
super(v);
aImage = (ImageView) v.findViewById(R.id.img_answer);
reply = (ImageView) v.findViewById(R.id.imgReplay);
qText = (TextView) v.findViewById(R.id.txt_question);
aText = (TextView) v.findViewById(R.id.txt_answer);
aUserName = (TextView) v.findViewById(R.id.txt_a_user_name);
qUserName = (TextView) v.findViewById(R.id.txt_q_user_name);
layoutAnswer = (LinearLayout) v.findViewById(R.id.answer_box_item);
}
}
public static class ViewHolderQAFile extends RecyclerView.ViewHolder {
ImageView qImage;
ImageView aImage;
ImageView reply;
TextView qText;
TextView aText;
TextView aUserName;
TextView qUserName;
LinearLayout layoutAnswer;
public ViewHolderQAFile(View v) {
super(v);
qImage = (ImageView) v.findViewById(R.id.img_question);
aImage = (ImageView) v.findViewById(R.id.img_answer);
reply = (ImageView) v.findViewById(R.id.imgReplay);
qText = (TextView) v.findViewById(R.id.txt_question);
aText = (TextView) v.findViewById(R.id.txt_answer);
aUserName = (TextView) v.findViewById(R.id.txt_a_user_name);
qUserName = (TextView) v.findViewById(R.id.txt_q_user_name);
layoutAnswer = (LinearLayout) v.findViewById(R.id.answer_box_item);
}
}
public static class ViewHolderUnsent extends RecyclerView.ViewHolder {
TextView unSentQuestion;
TextView unSentReplyText;
ImageView unSentImage;
public ViewHolderUnsent(View v) {
super(v);
unSentQuestion = (TextView) v.findViewById(R.id.txt_unSend_question);
unSentReplyText = (TextView) v.findViewById(R.id.txt_reply_unSend_question);
unSentImage = (ImageView) v.findViewById(R.id.img_unSend_question);
}
}
public static class ViewHolderReply extends RecyclerView.ViewHolder {
TextView replyPastQ;
TextView replyPastA;
TextView replyCurrentQ;
TextView replyCurrentA;
LinearLayout layoutAnswer;
ImageView imgReplay;
public ViewHolderReply(View v) {
super(v);
replyPastQ = (TextView) v.findViewById(R.id.reply_txt_past_question);
replyPastA = (TextView) v.findViewById(R.id.right_reply_txt_past_answer);
replyCurrentQ = (TextView) v.findViewById(R.id.reply_txt_current_question);
replyCurrentA = (TextView) v.findViewById(R.id.right_reply_txt_current_answer);
layoutAnswer = (LinearLayout) v.findViewById(R.id.answer_box_item);
imgReplay = (ImageView) v.findViewById(R.id.imgReplay);
}
}
#Override
public int getItemViewType(int position) {
/* *****************************Handling Inline Parents**************
* *
* 1 for item_message_no_file
* 2 for item_message_question_has_file
* 3 for item_message_answer_has_file
* 4 for item_message_q_a_has_file
* */
if (chatArray.get(position).isNoFile()) {
return 1;
} else if (chatArray.get(position).isMineUnSend()) {
//UnSend
return 2;
} else if (chatArray.get(position).isReply()) {
//Has Reply
return 3;
} else if (chatArray.get(position).isqHasFile()) {
//At this position q has file
return 4;
} else if (chatArray.get(position).isaHasFile()) {
//At this position a has file
return 5;
} else {
//At this position q and a have file
return 6;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new View
//No File
final View item_message_no_file = LayoutInflater.from(mContext).inflate(R.layout.item_message_no_file, parent, false);
//Not Send
final View item_message_un_send = LayoutInflater.from(mContext).inflate(R.layout.item_message_un_sent, parent, false);
//Reply
final View item_message_reply = LayoutInflater.from(mContext).inflate(R.layout.item_message_reply, parent, false);
//Question has File
final View item_message_q_has_file = LayoutInflater.from(mContext).inflate(R.layout.item_message_question_has_file, parent, false);
//Answers has File
final View item_message_a_has_file = LayoutInflater.from(mContext).inflate(R.layout.item_message_answer_has_file, parent, false);
//Question and Answer have file
final View item_message_q_a_has_file = LayoutInflater.from(mContext).inflate(R.layout.item_message_q_a_has_file, parent, false);
if (viewType == 1) {
return new ViewHolderNoFile(item_message_no_file); //For item_message_no_file
} else if (viewType == 2) {
return new ViewHolderUnsent(item_message_un_send); //For item_message_un_send
} else if (viewType == 3) {
return new ViewHolderReply(item_message_reply); //For item_message_reply
} else if (viewType == 4) {
return new ViewHolderQFile(item_message_q_has_file); //For item_message_q_has_file
} else if (viewType == 5) {
return new ViewHolderAFile(item_message_a_has_file); //For item_message_a_has_file
} else {
return new ViewHolderQAFile(item_message_q_a_has_file); //For item_message_q_a_has_file
}
}
/**
* add sent message to adapter
*
* #ArrayList<ChatModel> chatArray of messages
*/
public void addItem(ChatModel newMessage) {
Log.i("CHAT_ADAPTER", "CHAT ARRAY SIZE: " + this.chatArray.size());
this.chatArray.add(newMessage);
//notifyItemInserted(this.chatArray.size()-1);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
String question;
CourseForumModel cfm = chatArray.get(holder.getAdapterPosition()).getCourseForumModel();
switch (holder.getItemViewType()) {
case 1: //For item_message_no_file
ViewHolderNoFile vhNoFile = (ViewHolderNoFile) holder;
//Set userName of Answer
setUserName(vhNoFile.aUserName, cfm.getCourseForumAUserName());
//Set userName of Question
setUserName(vhNoFile.qUserName, cfm.getCourseForumQUserName());
//Set Question Text
setMessage(vhNoFile.qText, cfm.getCourseForumQuestion());
//Set Answer Text
setMessage(vhNoFile.aText, cfm.getCourseForumAnswer());
vhNoFile.reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentForum.onEvent(fragmentForum, chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumId());
}
});
// check if answer text is empty get answer layout gone
if (vhNoFile.aText.getText() == "") {
vhNoFile.layoutAnswer.setVisibility(View.INVISIBLE);
} else {
vhNoFile.layoutAnswer.setVisibility(View.VISIBLE);
}
break;
case 2: //For item_message_unSent
ViewHolderUnsent vhUnsent = (ViewHolderUnsent) holder;
SendChatModel unSendChat = chatArray.get(holder.getAdapterPosition()).getUnSendChats();
question = unSendChat.getCourseForum().getCourseForumQuestion();
int hasFile = unSendChat.getHasFile();
if (unSendChat.getCourseForum().getCourseForumQuestion() != null) {
vhUnsent.unSentQuestion.setText(question);
} else {
vhUnsent.unSentQuestion.setText("");
}
if (unSendChat.getCourseForum().getCourseForumReplyTo() > 0) {
vhUnsent.unSentReplyText.setText(unSendChat.getCourseForum().getReplyToSummary());
} else {
vhUnsent.unSentReplyText.setText("");
}
//This UnSend Message has a file
if (hasFile == 1) {
String filePath = chatArray.get(holder.getAdapterPosition()).getUnSendChats().getFilePath();
Picasso
.with(mContext)
.load(new File(filePath))
.resize(64, 64)
.into(vhUnsent.unSentImage);
} else {
vhUnsent.unSentImage.setImageResource(android.R.color.transparent);
}
break;
case 3: //For item_message_Reply
ViewHolderReply vRTReply = (ViewHolderReply) holder;
vRTReply.replyPastQ.setText(chatArray.get(holder.getAdapterPosition()).getReplayedMessage().getCourseForumQuestion());
vRTReply.replyPastA.setText(chatArray.get(holder.getAdapterPosition()).getReplayedMessage().getCourseForumAnswer());
vRTReply.replyCurrentQ.setText(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumQuestion());
vRTReply.replyCurrentA.setText(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAnswer());
vRTReply.imgReplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentForum.onEvent(fragmentForum, chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumId());
}
});
// check if answer text is empty get answer layout gone
if (chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAnswer().equals("")) {
vRTReply.layoutAnswer.setVisibility(View.INVISIBLE);
} else {
vRTReply.layoutAnswer.setVisibility(View.VISIBLE);
}
break;
case 4: //For item_message_q_has_file
ViewHolderQFile vhQFile = (ViewHolderQFile) holder;
setUserName(vhQFile.qUserName, cfm.getCourseForumQUserName());
setUserName(vhQFile.aUserName, cfm.getCourseForumAUserName());
//Set Question Text
setMessage(vhQFile.qText, cfm.getCourseForumQuestion());
//Set Answer Text
setMessage(vhQFile.aText, cfm.getCourseForumAnswer());
loadImage(
vhQFile.qImage,
holder.getAdapterPosition(),
chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumQFile()
);
vhQFile.qImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumQFile());
}
});
vhQFile.reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentForum.onEvent(fragmentForum, chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumId());
}
});
// check if answer text is empty get answer layout gone
if (vhQFile.aText.getText() == "") {
vhQFile.layoutAnswer.setVisibility(View.INVISIBLE);
} else {
vhQFile.layoutAnswer.setVisibility(View.VISIBLE);
}
break;
case 5: //For item_message_a_has_file
ViewHolderAFile vhAFile = (ViewHolderAFile) holder;
setUserName(vhAFile.qUserName, cfm.getCourseForumQUserName());
setUserName(vhAFile.aUserName, cfm.getCourseForumAUserName());
//Set Question Text
setMessage(vhAFile.qText, cfm.getCourseForumQuestion());
//Set Answer Text
setMessage(vhAFile.aText, cfm.getCourseForumAnswer());
loadImage(
vhAFile.aImage,
holder.getAdapterPosition(),
chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAFile()
);
vhAFile.aImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAFile());
}
});
vhAFile.reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentForum.onEvent(fragmentForum, chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumId());
}
});
// check if answer text is empty get answer layout gone
if (vhAFile.aText.getText() == "") {
vhAFile.layoutAnswer.setVisibility(View.INVISIBLE);
} else {
vhAFile.layoutAnswer.setVisibility(View.VISIBLE);
}
break;
case 6: //For item_message_q_a_has_file
ViewHolderQAFile vhQAFile = (ViewHolderQAFile) holder;
setUserName(vhQAFile.qUserName, cfm.getCourseForumQUserName());
setUserName(vhQAFile.aUserName, cfm.getCourseForumAUserName());
//Set Question Text
setMessage(vhQAFile.qText, cfm.getCourseForumQuestion());
//Set Answer Text
setMessage(vhQAFile.aText, cfm.getCourseForumAnswer());
//Here Both Question and Answer have file
loadImage(
vhQAFile.qImage,
holder.getAdapterPosition(),
chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumQFile()
);
loadImage(
vhQAFile.aImage,
holder.getAdapterPosition(),
chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAFile()
);
vhQAFile.qImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumQFile());
}
});
vhQAFile.aImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumAFile());
}
});
vhQAFile.reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentForum.onEvent(fragmentForum, chatArray.get(holder.getAdapterPosition()).getCourseForumModel().getCourseForumId());
}
});
// check if answer text is empty get answer layout gone
if (vhQAFile.aText.getText() == "") {
vhQAFile.layoutAnswer.setVisibility(View.INVISIBLE);
} else {
vhQAFile.layoutAnswer.setVisibility(View.VISIBLE);
}
break;
}
}
public void update(ArrayList<ChatModel> updatedArray) {
chatArray.clear();
chatArray.addAll(updatedArray);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return chatArray.size();
}
private void setUserName(TextView textView, String name) {
if (name.length() > 0) {
textView.setText(name);
}
}
private void setMessage(TextView textView, String text) {
if (text.length() > 0) {
textView.setText(text);
}
}
private void loadImage(final ImageView view, int position, final int fileId) {
FileModel fileModel = InternetService.getSingleFile(fileId);
String imageAddress = G.DIR_APP + fileModel.getFileName() + "." + fileModel.getFileExtension();
Picasso
.with(mContext)
.load(new File(imageAddress))
.resize(64, 64)
.into(view);
}
private void showDialog(int fileId) {
FileModel fileModel = InternetService.getSingleFile(fileId);
final Bitmap bitmap = BitmapFactory.decodeFile(G.DIR_APP + fileModel.getFileName() + "." + fileModel.getFileExtension());
final Dialog dialog = new Dialog(mContext, R.style.CustomDialog);
dialog.setContentView(R.layout.activity_image_view);
ImageView img = (ImageView) dialog.findViewById(R.id.imgShow);
img.setImageBitmap(bitmap);
Button dismissButton = (Button) dialog.findViewById(R.id.dissbtn);
dismissButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
And this is an image of recyclerView:
Update:
I got Log of positions in onBindViewHolder method Ans I scrolled from bottom to top Then I got this items in logCat 0-1-2-3-4-5-6-12-13-14-15-16-17!
Items 7-8-9-1-11 doesn't logged!
This is really Important for me.
Thank you for your answers.
RecyclerView reuses existing Views to perform better. Therefore onBindViewHolder gets called and the previous View is updated with the new Values and Styles. If you don't replace an existing Value with the new one you will still see the old one.
From the RecyclerView Docs.
If the user scrolls the list, the Android Support Library brings the already-prepared view holders into view, and creates and binds new ones as necessary. It does not immediately destroy the view holders that have scrolled out of sight; they are kept available, in case the user scrolls back. However, after a certain number of view holders have been created, the Android Support Library does not create new ones. Instead, it rebinds existing view holders as needed by calling onBindViewHolder() for them, specifying a new position. That method updates the view holder's contents, but it reuses the view that was already created for that view holder. The method does not have to perform costly actions like building or inflating a new view.
As Amod Gokhale mentioned. In most cases wrong views appear because of if statements with missing else.
For all your position which you use to retrieve your item inside onBindViewHolder, you should use holder.getAdapterPosition().
P.S. Not related to your question. In your onCreateViewHolder, you are inflating all types of View first and then returning only the one you need based on your viewType. You should check the viewType first and then only inflate the one View you need.
Finally I found the problem.
I am using a viewPager and 3 fragments in it. When I open my chat fragment that contains mentioned recyclerView and scroll up and down all the items will be in wrong places! So I made a Log of the items position in onBindViewHolder() as #Ahmadul Hoq said to me. Then I found items will not go to onBind in serially!
finally I found this problem was about fragment and viewPager.Then I just used of this method to set my recyclerView again when user sweap it to watch.Like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser){
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//Setting up recycler view for Chats
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
rvMain.setLayoutManager(mLayoutManager);
mAdapter = new chatAdapter(populateCourseChats(), getActivity() , this);
rvMain.setAdapter(mAdapter);
scrollRecyclerToBottom(); //Scroll recyclerView to bottom
}
}
And Now everything is fine.
But I didn't find it out why this happens?!
If you know Please tell me.
Thank you.
Related
I need to use notifyDataSetChanged() and setText a value to a TextView inside onBindViewHolder. I tried to use both inside onClick method,
qtyIncrease.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityText.setText("Good");
toatlPriceText.setText("250");
notifyDataSetChanged();
}
});
My adapter class,
public class CartCardviewAdapter extends RecyclerView.Adapter<CartCardviewAdapter.MyViewHolder> {
private Context context;
private ArrayList<CartCardviewModel> dataSet;
private ShoppingCart shoppingCart;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView itemNameText, itemTypeText, itemDescText, unitPriceText, toatlPriceText, quantityText;
ImageView itemImage, removeIcon, qtyIncrease, qtyDecrease;
public MyViewHolder(final View itemView) {
super(itemView);
this.itemNameText = (TextView) itemView.findViewById(R.id.item_name_text);
this.itemTypeText = (TextView) itemView.findViewById(R.id.item_type_text);
this.itemDescText = (TextView) itemView.findViewById(R.id.item_desc_text);
this.unitPriceText = (TextView) itemView.findViewById(R.id.item_unit_price_text);
this.toatlPriceText = (TextView) itemView.findViewById(R.id.item_total_price_text);
this.quantityText = (TextView) itemView.findViewById(R.id.item_quantity_text);
this.itemImage = (ImageView) itemView.findViewById(R.id.item_image);
this.removeIcon = (ImageView) itemView.findViewById(R.id.item_remove_icon);
this.qtyIncrease = (ImageView) itemView.findViewById(R.id.cart_quantity_increase);
this.qtyDecrease = (ImageView) itemView.findViewById(R.id.cart_quantity_decrease);
}
}
public CartCardviewAdapter(ArrayList<CartCardviewModel> data) {
this.dataSet = data;
}
#Override
public CartCardviewAdapter.MyViewHolder onCreateViewHolder(final ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cart_cardview_layout, parent, false);
CartCardviewAdapter.MyViewHolder myViewHolder = new CartCardviewAdapter.MyViewHolder(view);
context = parent.getContext();
return myViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(final CartCardviewAdapter.MyViewHolder holder, final int listPosition) {
shoppingCart = MainActivity.getCartInstance().getCart();
TextView itemNameText = holder.itemNameText;
TextView itemTypeText = holder.itemTypeText;
TextView itemDescText = holder.itemDescText;
TextView unitPriceText = holder.unitPriceText;
final TextView toatlPriceText = holder.toatlPriceText;
final TextView quantityText = holder.quantityText;
ImageView itemImage = holder.itemImage;
ImageView removeIcon = holder.removeIcon;
ImageView qtyIncrease = holder.qtyIncrease;
ImageView qtyDecrease = holder.qtyDecrease;
itemNameText.setText(dataSet.get(listPosition).getItemName());
itemTypeText.setText(dataSet.get(listPosition).getItemType());
itemDescText.setText(dataSet.get(listPosition).getItemDescription());
unitPriceText.setText(String.valueOf(dataSet.get(listPosition).getUnitPrice()));
toatlPriceText.setText(String.valueOf(dataSet.get(listPosition).getTotalPrice()));
String qty;
if (dataSet.get(listPosition).getItemQuantity() < 9) {
qty = "0" + String.valueOf(dataSet.get(listPosition).getItemQuantity());
} else {
qty = String.valueOf(dataSet.get(listPosition).getItemQuantity());
}
quantityText.setText(qty);
Picasso.with(context).load(dataSet.get(listPosition).getItemImageUrl()).into(itemImage);
removeIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(v.getContext(), String.valueOf(listPosition), Toast.LENGTH_SHORT).show();
shoppingCart.removeItem(listPosition);
dataSet.remove(listPosition);
notifyDataSetChanged();
}
});
qtyIncrease.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shoppingCart.increaseItemQuantity(listPosition);
quantityText.setText(String.valueOf(shoppingCart.getItemQuantity(listPosition)));
toatlPriceText.setText(String.valueOf(shoppingCart.getTotalPrice(listPosition)));
notifyDataSetChanged();
}
});
qtyDecrease.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (shoppingCart.getItemQuantity(listPosition) == 1) {
Toast.makeText(v.getContext(), "Already Minimum Quantity is Reached", Toast.LENGTH_SHORT).show();
} else {
shoppingCart.decreaseItemQuantity(listPosition);
quantityText.setText(String.valueOf(shoppingCart.getItemQuantity(listPosition)));
toatlPriceText.setText(String.valueOf(shoppingCart.getTotalPrice(listPosition)));
notifyDataSetChanged();
}
}
});
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
but both don't work at a click. I need to go back and come to see the affected change. I could't understand the problem. Please help me
First This line #RequiresApi(api = Build.VERSION_CODES.N) is for too restrictive, take into consideration lower levels down the line. There are many ways to approach this problem, first you can use a RecyclerView.OnItemTouchListener to the recycler hosting the adaptor. Here is a detailed tutorial describing single and long click , Link. Another approach is the interface segration principle.
In the adaptor class, create a interface, with one method
method signature (View view, int position), depicts a view clicked with repective position in adaptor.
Declare a instance of this interface in the adaptor
Modify the contructor to accept a interface of that type
Let the class with the recylcler view instance implement above interface
Pass a new instance to the contructor in the implemented class
Then in the overriden method, change your text and call adaptor.notifyItemChanged(position)
oh, also, in the adaptor class where the views gets init , set onClicklistener with the interface instance.
This tutorial describes exactly the above in great detail,link.
Your welcome!
the click won't trigger from there , you need to set the click listener of the Image View "qtyIncrease" inside the ViewHolder not in "OnBindViewHolder"
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView itemNameText, itemTypeText, itemDescText, unitPriceText, toatlPriceText, quantityText;
ImageView itemImage, removeIcon, qtyIncrease, qtyDecrease;
public MyViewHolder(final View itemView) {
super(itemView);
this.itemNameText = (TextView) itemView.findViewById(R.id.item_name_text);
this.itemTypeText = (TextView) itemView.findViewById(R.id.item_type_text);
this.itemDescText = (TextView) itemView.findViewById(R.id.item_desc_text);
this.unitPriceText = (TextView) itemView.findViewById(R.id.item_unit_price_text);
this.toatlPriceText = (TextView) itemView.findViewById(R.id.item_total_price_text);
this.quantityText = (TextView) itemView.findViewById(R.id.item_quantity_text);
this.itemImage = (ImageView) itemView.findViewById(R.id.item_image);
this.removeIcon = (ImageView) itemView.findViewById(R.id.item_remove_icon);
this.qtyIncrease = (ImageView) itemView.findViewById(R.id.cart_quantity_increase);
this.qtyDecrease = (ImageView) itemView.findViewById(R.id.cart_quantity_decrease);
qtyIncrease.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityText.setText("Good");
toatlPriceText.setText("250");
notifyDataSetChanged();
}
});
}
I have an custom listview which contains button and textview. The textview visibility is gone. When the button text is "email" and if I click on button the textview should display below the button. But the last textview is always getting visible.
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
wantedUsers du = wusers.get(i);
final String mcontact = du.mcontact;
if(view==null) {
viewholder = new viewholder();
view = LayoutInflater.from(ws).inflate(R.layout.wantedmoviecustom, null);
viewholder.mcontwcustom = (Button)view.findViewById(R.id.mcontwcustom);
viewholder.mdisplayemail = (TextView) view.findViewById(R.id.mdisplayemail);
view.setTag(viewholder);
} else {
viewholder = (viewholder) view.getTag();
}
viewholder.mdisplayemail.setVisibility(View.GONE);
if(mcontact.contains("#")) {
viewholder.mcontwcustom.setText("Show Email");
viewholder.mdisplayemail.setText(mcontact);
} else {
viewholder.mcontwcustom.setText("Call");
}
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
// viewholder.mdisplayemail.setText(mcontact);
}
else
{
Uri call = Uri.parse("tel:" + mcontact);
Intent surf = new Intent(Intent.ACTION_DIAL, call);
ws.startActivity(surf);
}
}
});
viewholder.mcontwcustom.setTag(i);
return view;
}
below is my getview from custom adapter. So how can I make a textview visbile when a button clicked on particular row.
First, you need to create a Global variable
int positionOfButtonClick = -1;
then you need to update your position on button click and need to call notifyDataSetChanged();
like - :
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
positionOfButtonClick = i;
notifyDataSetChanged();
//your other code
});
Then, in getView
you need to check the position and need to VISIBLE your textView like -:
if(i==positionOfButtonClick ){
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
}
Now, your getView should be-:
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
wantedUsers du = wusers.get(i);
final String mcontact = du.mcontact;
if(view==null) {
viewholder = new viewholder();
view = LayoutInflater.from(ws).inflate(R.layout.wantedmoviecustom, null);
viewholder.mcontwcustom = (Button)view.findViewById(R.id.mcontwcustom);
viewholder.mdisplayemail = (TextView) view.findViewById(R.id.mdisplayemail);
if(i==positionOfButtonClick ){
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
}else{
viewholder.mdisplayemail.setVisibility(View.GONE);
}
view.setTag(viewholder);
} else {
viewholder = (viewholder) view.getTag();
}
if(mcontact.contains("#")) {
viewholder.mcontwcustom.setText("Show Email");
viewholder.mdisplayemail.setText(mcontact);
} else {
viewholder.mcontwcustom.setText("Call");
}
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
positionOfButtonClick = i;
notifyDataSetChanged();
}
else
{
Uri call = Uri.parse("tel:" + mcontact);
Intent surf = new Intent(Intent.ACTION_DIAL, call);
ws.startActivity(surf);
}
}
});
viewholder.mcontwcustom.setTag(i);
return view;
}
Change in code as mention below, I think it help you.
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
// viewholder.mdisplayemail.setText(mcontact);
}
I have a recyclerView that use a adapter to bind view and perform click button on each view. But when i click on item 1, then the item += 7(ex: row 0, 7, 14,... will be changed UI due to onClick event trigger) also click too. Please help me.
Here's my viewholder code:
public MatchItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View matchView = inflater.inflate(R.layout.match_item, parent, false);
MatchItemViewHolder matchItemViewHolder = null;
matchItemViewHolder = new MatchItemViewHolder(matchView);
return matchItemViewHolder;
}
I call onClick event here, i have to delete some definition because stackoverflow not let me post too much codes:
public class MatchItemViewHolder extends RecyclerView.ViewHolder {
public TextView txtTeamA;
public TextView txtTeamB;
public ImageView imvLive;
public Button btnPredict;
public boolean isLive = false;
public boolean hasUnderOver = false;
public MatchItemViewHolder(final View itemView) {
super(itemView);
txtTeamA = (TextView) itemView.findViewById(R.id.match_item_txt_teamA);
txtTeamB = (TextView) itemView.findViewById(R.id.match_item_txt_teamB);
txtRatioA = (TextView) itemView.findViewById(R.id.match_item_txt_ratioA);
txtRatioB = (TextView) itemView.findViewById(R.id.match_item_txt_ratioB);
txtPercentage = (TextView) itemView.findViewById(R.id.match_item_txt_percentage);
txtBetDirection = (TextView) itemView.findViewById(R.id.match_item_txt_betDirection);
txtMatchBo = (TextView) itemView.findViewById(R.id.match_item_txt_matchBo);
txtMatchNote = (TextView) itemView.findViewById(R.id.match_item_txt_matchNote);
txtMatchTime = (TextView) itemView.findViewById(R.id.match_item_txt_MatchTime);
txtMatchHour = (TextView) itemView.findViewById(R.id.match_item_txt_matchHour);
txtTourName = (TextView) itemView.findViewById(R.id.match_item_txt_TourName);
imvTeamA = (ImageView) itemView.findViewById(R.id.match_item_imv_TeamA);
imvTeamB = (ImageView) itemView.findViewById(R.id.match_item_imv_TeamB);
imvGameImage = (ImageView) itemView.findViewById(R.id.match_item_imv_GameImage);
imvLive = (ImageView) itemView.findViewById(R.id.match_item_imv_LiveImage);
btnPredict = (Button) itemView.findViewById(R.id.match_item_btn_Predict);
//set Item Click listener for item
btnPredict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean winner = false;
PredictController predictController = new PredictController();
winner = predictController.getWinner(txtTeamA.getText().toString(), txtTeamB.getText().toString());
if (winner) {
txtBetDirection.setText("Xuôi nha");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
txtTeamA.setTextColor(context.getResources().getColor(R.color.colorPrimary, null));
txtTeamB.setTextColor(context.getResources().getColor(R.color.primary_text, null));
}else{
txtTeamA.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
txtTeamB.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
}
} else {
txtBetDirection.setText("Ngược nhé");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
txtTeamB.setTextColor(context.getResources().getColor(R.color.colorPrimary, null));
txtTeamA.setTextColor(context.getResources().getColor(R.color.primary_text, null));
}else{
txtTeamB.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
txtTeamA.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
}
}
}
});
}
}
And OnBindViewHolder Code:
#Override
public void onBindViewHolder(MatchItemViewHolder holder, int position) {
MatchesModel matchesModel = lstMatchItem.get(position);
holder.txtTeamA.setText(matchesModel.teamA);
holder.txtTeamB.setText(matchesModel.teamB);
holder.txtRatioA.setText(matchesModel.teamARatio);
holder.txtRatioB.setText(matchesModel.teamBRatio);
holder.txtPercentage.setText(matchesModel.teamPercentage);
holder.txtMatchBo.setText(matchesModel.matchBo);
if (matchesModel.matchDate != null) {
holder.txtMatchTime.setText(matchesModel.matchDate);
holder.txtMatchHour.setText(matchesModel.matchDate.split("\\s")[1]);
}
holder.txtMatchNote.setText(matchesModel.matchNote);
Picasso.with(context).load(matchesModel.teamAImage).fit().into(holder.imvTeamA);
Picasso.with(context).load(matchesModel.teamBImage).fit().into(holder.imvTeamB);
holder.txtTourName.setText(matchesModel.tourName);
Picasso.with(context).load(matchesModel.gameImage).fit().into(holder.imvGameImage);
UPDATE: I have figure it out how to solve the problem. Just use rclMatchItem.setItemViewCacheSize(100);
Set recyclerView cache view is the problem maybe default it's 7.
Thank you guys anyway.
Thanks guys, i found the solution for this problem.
In my Recycler Apdater I implement
public long getItemId(int position) {return position;}
Then use ItemCachedView for recyclerView rclMatchItem.setItemViewCacheSize(100);
And i never get repeat item every 7 rows anymore.
Change your onClickListener from ViewController to onBindView()
#Override
public void onBindViewHolder(MatchItemViewHolder holder, int position) {
holder.btnPredict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean winner = false;
PredictController predictController = new PredictController();
winner = predictController.getWinner(txtTeamA.getText().toString(), txtTeamB.getText().toString());
if (winner) {
txtBetDirection.setText("Xuôi nha");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
txtTeamA.setTextColor(context.getResources().getColor(R.color.colorPrimary, null));
txtTeamB.setTextColor(context.getResources().getColor(R.color.primary_text, null));
}else{
txtTeamA.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
txtTeamB.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
}
} else {
txtBetDirection.setText("Ngược nhé");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
txtTeamB.setTextColor(context.getResources().getColor(R.color.colorPrimary, null));
txtTeamA.setTextColor(context.getResources().getColor(R.color.primary_text, null));
}else{
txtTeamB.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
txtTeamA.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
}
}
}
});
}
Create a boolean variable showWhoWinner varibale in your MatchesModel object.
In onBindViewHolder method setup click listener and make value of showWhoWinner variable invert.
btnPredict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
matchesModel.setShowWhoWinner(!matchesModel.isShowWhoWinner);
notifyItemChanged(position);
}
And then in onBindViewHolder, put that condition of color changing:
if(matcherModel.isShowWhoWinner()){
boolean winner = false;
PredictController predictController = new PredictController();
winner = predictController.getWinner(txtTeamA.getText().toString(), txtTeamB.getText().toString());
if (winner) {
//Winner Color
} else {
//Default color
}
}
else{
//Default color
}
Hope this helps
I'm using RecyclerView, I have one ImageButton as Child view, I'm changing the background of that ImageButton on click.
Now my problem is when change Image of ImageButton by clicking and than scroll up again scroll to the top, the state of set to the initial stage. I tried everything but its not happening. help me with that.
My Adapter class
public class ViewAllAdapter extends RecyclerView.Adapter<ProductHolder> {
int[] objects;
Context context;
Boolean flag = false;
public ViewAllAdapter(int[] objects, Context context) {
super();
this.objects = objects;
this.context = context;
}
#Override
public int getItemCount() {
return objects.length;
}
#Override
public void onBindViewHolder(final ProductHolder arg0, int arg1) {
arg0.title.setText("Product" + arg1 + 1);
arg0.aPrice.setPaintFlags(arg0.aPrice.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
arg0.aPrice.setText("\u20B9" + " " + "5000");
arg0.off.setText("56% off");
arg0.price.setText("\u20B9" + " " + "2300");
arg0.mainImage.setImageResource(objects[arg1]);
arg0.ratings.setRating(4f);
arg0.clickme.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,
ProductDetailsPage.class);
startActivity(i);
}
});
arg0.wish.setBackgroundResource(R.drawable.heart);
arg0.wish.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
arg0.wish.setBackgroundResource(R.drawable.heartfade);
YoYo.with(Techniques.Tada).duration(550)
.playOn(arg0.wish);
Toast.makeText(context, "Product Added to wish list..",
Toast.LENGTH_SHORT).show();
flag = true;
} else {
arg0.wish.setBackgroundResource(R.drawable.heart);
Toast.makeText(context,
"Product Removed to wish list..",
Toast.LENGTH_SHORT).show();
flag = false;
}
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
LayoutInflater inflater = LayoutInflater.from(arg0.getContext());
View view = inflater.inflate(R.layout.viewall_item, arg0, false);
return new ProductHolder(view);
}
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView title;
protected TextView aPrice;
protected TextView off;
protected TextView price;
protected ImageView mainImage;
protected RatingBar ratings;
protected ImageButton wish;
protected RelativeLayout clickme;
public ProductHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.productName);
aPrice = (TextView) itemView
.findViewById(R.id.productActualPrice);
off = (TextView) itemView.findViewById(R.id.offPrice);
price = (TextView) itemView.findViewById(R.id.productPrice);
mainImage = (ImageView) itemView
.findViewById(R.id.productImage);
wish = (ImageButton) itemView.findViewById(R.id.addToWishList);
ratings = (RatingBar) itemView
.findViewById(R.id.productRatings);
clickme = (RelativeLayout) itemView
.findViewById(R.id.clickToGO);
}
}
}
And in My MainActicity I'm doing
rv = (RecyclerView) findViewById(R.id.gvViewAll);
rv.setHasFixedSize(true);
GridLayoutManager glm = new GridLayoutManager(getApplicationContext(),
2);
rv.setLayoutManager(glm);
final ViewAllAdapter adp = new ViewAllAdapter(productImage,
getApplicationContext());
rv.setAdapter(adp);
rvh = (RecyclerViewHeader) findViewById(R.id.header);
rvh.attachTo(rv, true);
Thanks for any help.
As per your Custom RecyclerView adapter, I suggest you to use HashMap to store Values. After all Data Model is best option to load data in to RecyclerView.
HashMap<Integer, Integer> hashMapTest = new HashMap<>();
When user click on ImageButton then add following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Code of Product Added to wish list..
hashMapTest.put(getPosition(), 1);
} else {
// Code of Product Removed to wish list..
hashMapTest.put(getPosition(), 0);
}
}
});
In your onBindViewHolder(ProductHolder holder, int position) add following code
if(hashMapTest.get(position) != null && hashMapTest.get(position) != false) {
// Show your ImageButton color Product Added to wish list..
} else {
// Show your ImageButton color Product Removed to wish list..
}
Hope it helps you.
I have a listview in which I inflate a layout with multiple textviews and buttons. I understand to get the text from a view that was clicked is ((Textview)view.... However I am trying to get the text from the specific textview that is located in the layout in which the user clicked. I have tried using OnItemClick but when I use this the item must be focused before the any of the buttons functions work. I resorted to and prefer using onClickListeners in the getView method of my custom adapter. So simply put, how do I click a Button and get the text that is in TextView that is located in the appropriate inflated layout list view item, given that since each inflated layout is considered as one list item?
UPDATE
Here are pictures to clarify what i am looking for. Both layouts are members of a listview.
I want to click the button with the date on it and get the text from the textview in the middle of the layout. However when I click the button with the date on it, I can only get the text from the textview in the middle of the layout of the last child. If "My Party" is the first child in the listview and "3303 going away service..." is the second child, when I click the date button the code in my custom adapter returns the text from the last loaded text in the view which will be "3303 going away service". What I am trying to do is when I click the date button on "My party", get the text "My party". Like wise with the second child.
Here is the getView() in my custom adapter.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder = new ViewHolder();
positionHolder = position;
Log.i("Position", "" + position);
if(convertView == null) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.post_layout, parent, false);
postLayout = convertView;
viewHolder.unameTV = (TextView) postLayout.findViewById(R.id.postUnameTv);
viewHolder.unameTV.setText(viewContent.get(index));
viewHolder.unameTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Starting new intent
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
String username =((TextView)view).getText().toString();
in.putExtra("username", username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
viewHolder.fillSpace = (TextView)postLayout.findViewById(R.id.posthelpSpace);
viewHolder.fillSpace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
viewHolder.image = (ImageView) postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewContent.get(index + 1), viewHolder.image, options);
viewHolder.addToCalendarButton = (TextView) postLayout.findViewById(R.id.addToCalendarButton);
viewHolder.addToCalendarButton.setText(viewContent.get(index + 2));
viewHolder.addToCalendarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.MONTH, 2);
long time = cal.getTime().getTime();
Uri.Builder builder =
CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
builder.appendPath(Long.toString(time));
Intent intent =
new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);
title = testText.getText().toString();
Log.i("Title", "" + title);
intent.putExtra("title", title); // **NOT WORKING**
startActivity(intent);
}
});
viewHolder.eventTitle = (TextView) postLayout.findViewById(R.id.postTitleTV);
viewHolder.eventTitle.setText(viewContent.get(index + 3));
viewHolder.eventTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = ((TextView)view).getText().toString();
Log.i("TITLE", "" + title);
}
});
testText = viewHolder.eventTitle;
viewHolder.eventImage = (ImageView) postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewContent.get(index + 4), viewHolder.eventImage, options);
viewHolder.likesTV = (TextView) postLayout.findViewById(R.id.likesTV);
viewHolder.likesTV.setText("" + viewContent.get(index + 5));
viewHolder.planToAttendTV = (TextView) postLayout.findViewById(R.id.planToAttendTV);
viewHolder.planToAttendTV.setText(viewContent.get(index + 6));
viewHolder.addressTV = (TextView) postLayout.findViewById(R.id.postLocationTV);
viewHolder.addressTV.setText("" + viewContent.get(index + 7));
index = index + 8;
}
catch (IndexOutOfBoundsException ie)
{
ie.printStackTrace();
}
}
else
{
viewHolder = (ViewHolder) postLayout.getTag();
}
return postLayout;
}
Create a custom baseadapter and set on click listener for text view in the adapter. This will then be set for the specific text view corresponding to the position.
I think you already have custom BaseAdapter created, in the custom BaseAdapter setOnclicklistener of the textview to which you want the click to be registered.
Sample Code Below
public class M_Adapter extends BaseAdapter {
private LayoutInflater inflater = null;
private TextView contact_name;
private Context context;
private List<String> list;
private List<String> temp;
private Button btn;
public M_Adapter(Context context) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
list = new ArrayList<String>();
//add some values in list here
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
final View rowview = inflater.inflate(R.layout.contact_listrow, parent, false);
contact_name = (TextView) rowview.findViewById(R.id.excl_ppl_contact_name);
btn=(Button)rowview.findViewById(R.id.excl_ppl_btn);
contact_name.setText(list.get(temp));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("myapp", "text clicked " + contact_name.getText());
}
});
return rowview;
}
}
I solved this problem with two series of if/else statements. First, in my onBindViewHolder (your getView) I have some global String variables take on the value of the TextView I'm interested in. Second, in the onClick method, I have the ViewHolder tell me the position of the item clicked using the getPosition method. Last, I match the value of the position clicked with the String variables created in the first part and carry on from there.
public void onBindViewHolder(final ViewHolder holder, final int position) {
YelpAPI.businessNumber = position;
YelpAPI.queryAPI(YelpAPI.yelpApi, YelpAPI.yelpApiCli);
Picasso.with(mContext).load(YelpAPI.picture).into(holder.yelpPicture);
holder.textName.setText(YelpAPI.name);
holder.textRating.setText(YelpAPI.rating);
holder.textReviews.setText(YelpAPI.reviews);
holder.textAddressDetails.setText(YelpAPI.fullAddress);
holder.textInfo.setText(YelpAPI.moreInfo);
holder.textID.setText(YelpAPI.businessID);
---------- First...
if(position == 0){
firstBusiness = YelpAPI.businessID; //these three String variables get created above
} else if(position == 1){
secondBusiness = YelpAPI.businessID;
} else if (position == 2) {
thirdBusiness = YelpAPI.businessID;
}
holder.business.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
----------Second...
int specific = holder.getPosition();
----------Last...
String saveMe = "";
if(specific == 0){
saveMe = firstBusiness;
} else if(specific == 1){
saveMe = secondBusiness;
} else if(specific == 2){
saveMe = thirdBusiness;
}
Log.d("Clicked this item: ", String.valueOf(specific));`