View Changes While scrolling RecyclerView - android

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.

Related

Why RecyclerView Items appear in wrong positions?

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.

Overlay listview at bottom of viewpager and focus on current item

Hello Everyone I am Developing one Gallery app.
I have implemented Gridview and displayed images from server.when click on that image it will open one dialog and dialog contain viewpager and listview at bottom.
According to the viewpager position image it will smooth slide listview also.
Problem:I want to display overlay layer on listview and display only current item focused and other item are looks like blurish.
Here is my code
imagelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
imagdialog = new Dialog(MainActivity.this);
imagdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
imagdialog.setContentView(R.layout.imagelist);
imagdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(final DialogInterface arg0) {
// recreate();
selectedAdapter = new Sadapter(getApplicationContext(), arraylist);
imagelist.setAdapter(selectedAdapter);
}
});
photoid = arraylist.get(i).getId();
Log.v("Photoid111", "" + photoid);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(imagdialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
imagdialog.getWindow().setAttributes(lp);
viewpager = (ViewPager) imagdialog.findViewById(R.id.img);
final Button accept = (Button) imagdialog.findViewById(R.id.accept);
final Button reject = (Button) imagdialog.findViewById(R.id.reject);
final EditText cmnts = (EditText) imagdialog.findViewById(R.id.comnt);
ImageView closewin = (ImageView) imagdialog.findViewById(R.id.search_close_btn);
imglist = (RecyclerView) imagdialog.findViewById(R.id.imglist);
LinearLayoutManager sublimationmanager
= new LinearLayoutManager(imagdialog.getContext(), LinearLayoutManager.HORIZONTAL, false);
imglist.setLayoutManager(sublimationmanager);
cmnts.setText("" + arraylist.get(i).getCmnts());
cmnts.setSelection(cmnts.getText().length());
adaptor = new ViewPager_Adaptor(MainActivity.this, arraylist);
viewpager.setAdapter(adaptor);
viewpager.setCurrentItem(i);
img_adaptor = new Image_list(getApplicationContext(), arraylist);
imglist.setAdapter(img_adaptor);
imglist.smoothScrollToPosition(i);
pos = i;
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
photoid = arraylist.get(position).getId();
Log.v("Photoid", "" + photoid);
cmnts.setText("" + arraylist.get(position).getCmnts());
cmnts.setSelection(cmnts.getText().length());
imglist.smoothScrollToPosition(position);
pos = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
closewin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagdialog.dismiss();
selectedAdapter = new Sadapter(getApplicationContext(), arraylist);
imagelist.setAdapter(selectedAdapter);
}
});
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comments = cmnts.getText().toString();
Log.v("Photoid", "" + photoid);
Log.v("Photoid", "" + comments);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
mdialog = new Dialog(MainActivity.this);
mdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdialog.setContentView(R.layout.custom_progress_dialog);
mdialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
mdialog.setCancelable(false);
mdialog.show();
new Accept().execute(URL.amateurpath + "Accept");
} else {
if (imagdialog.isShowing())
imagdialog.dismiss();
nonetwork.setVisibility(View.VISIBLE);
main_layout.setVisibility(View.GONE);
noimg.setVisibility(View.GONE);
}
}
});
reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
comments = cmnts.getText().toString();
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
mdialog = new Dialog(MainActivity.this);
mdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdialog.setContentView(R.layout.custom_progress_dialog);
mdialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
mdialog.setCancelable(false);
mdialog.show();
new Reject().execute(URL.amateurpath + "Reject");
} else {
if (imagdialog.isShowing())
imagdialog.dismiss();
nonetwork.setVisibility(View.VISIBLE);
main_layout.setVisibility(View.GONE);
noimg.setVisibility(View.GONE);
}
}
});
imagdialog.show();
}
});
Here is my Viewpager Adaptor
public class ViewPager_Adaptor extends PagerAdapter {
private Context context;
ArrayList<CustomImages> data;
private LayoutInflater layoutInflater;
public ViewPager_Adaptor(Context context, ArrayList<CustomImages> arraylist) {
// TODO Auto-generated constructor stub
this.context = context;
data = arraylist;
Log.d("Abhi", data.toString());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("DATASIZE", String.valueOf(data.size()));
return data.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemview = layoutInflater.inflate(R.layout.viewpager_img, container, false);
final ImageView iimg = (ImageView) itemview.findViewById(R.id.imageview1);
ImageView clockw = (ImageView) itemview.findViewById(R.id.clock);
ImageView anticlockw = (ImageView) itemview.findViewById(R.id.anticlock);
clockw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
iimg.setRotation(iimg.getRotation() + 90);
}
});
anticlockw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
iimg.setRotation(iimg.getRotation() - 90);
}
});
Picasso.with(MainActivity.this).load(data.get(position).getUrl().replaceAll(" ", "%20")).placeholder(R.drawable.temp_img).error(R.drawable.no_media).into(iimg);
iimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intnt = new Intent(MainActivity.this, ImageShow.class);
intnt.putExtra("photo", data.get(position).getPhoto());
intnt.putExtra("url", data.get(position).getUrl());
startActivity(intnt);
}
});
container.addView(itemview);
return itemview;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
And finally Listview adapter is as follows
public class Image_list extends RecyclerView.Adapter<Image_list.MyViewHolder> {
ArrayList<CustomImages> arraylist1;
Context c;
public Image_list(Context c, ArrayList<CustomImages> arraylist) {
this.arraylist1 = arraylist;
this.c = c;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.inflate_image_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Log.v("Position of i", "" + pos);
// if (pos == position) {
// holder.img.setBackgroundResource(R.drawable.border);
// } else {
//
// }
Picasso
.with(this.c)
.load(arraylist1.get(position).getUrl().replaceAll(" ", "%20"))
.placeholder(R.drawable.temp_img) // can also be a drawable
.placeholder(R.drawable.temp_img)
.error(R.drawable.no_media)
.into(holder.img);
}
#Override
public int getItemCount() {
return arraylist1.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img;
public MyViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.catimg);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition();
viewpager.setCurrentItem(position);
}
});
}
}
}
Problem:I want to display overlay layer on listview and display only current item focused and other item are looks like blurish.
As concern to the problem i managed to slide list according to the viewpager slide but i want to display blurissh image and focus only one image from listview which is displayed in viewpager.
And display image from list at right of screen which is displayed in viewpager
Whenever one item is selected in the viewPager get the position of that item. Save the position of that item in a variable viewPagerPosition in the adapter. Then refresh the adapter by calling notifyDataSetChanged().
In the adapter have a view with certain transparency and make that visible as default.In adapter's onBindViewHolder check
if(position = viewPagerPosition){
transparentView.setVisibility(GONE);
} else{
transparentView.setVisibility(VISIBLE);
}
This should make the current view highlighted and other dimmed. If you want blur then you can use blur with the same condition.

ExpandableRecyclerAdapter How to force item to move up while expanding an item

This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView

RecyclerView items positions change or removed when scrolling

I have a problem that I have been trying to solve for too long but I can't know what causes the problem.
I have a marks list that contains Test objects and subject strings that I use as sections between marks, I use getClass() method to determine if an object is a string or Test, if it is a string, I hide the test's RelativeLayout, if it is a test then I hide the RelativeLayout of the subject. But when scrolling, items get removed and and re-added randomly.
my adapter's class:
public class MarksAdapter extends RecyclerView.Adapter<MarksAdapter.MyHolder>{
public class MyHolder extends RecyclerView.ViewHolder{
RelativeLayout card;
TextView title;
TextView total;
View divider;
int posito;
RelativeLayout group;
TextView groupTitle;
TextView groupMark;
public MyHolder(View itemView) {
super(itemView);
this.card = (RelativeLayout)itemView.findViewById(R.id.card);
this.title = (TextView)itemView.findViewById(R.id.title);
this.total = (TextView)itemView.findViewById(R.id.mark);
this.divider = itemView.findViewById(R.id.item_divider);
this.group = (RelativeLayout)itemView.findViewById(R.id.group);
this.groupTitle = (TextView)itemView.findViewById(R.id.group_title);
this.groupMark = (TextView)itemView.findViewById(R.id.group_mark);
}
}
final ArrayList marks;
Context ctx;
String selectedSem;
TestDatabase db;
public MarksAdapter(Context c, ArrayList marks,String sem,TestDatabase db,ArrayList<Integer> sections){
this.marks = marks;
ctx = c;
selectedSem = sem;
this.db = db;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(ctx).inflate(R.layout.mark_child, parent, false));
}
int lastPosition = -1;
int offset = 0;
#Override
public void onBindViewHolder(final MyHolder holder, final int positioner) {
holder.posito = positioner;
if(marks.get(holder.posito).getClass() == Test.class) {
holder.group.setVisibility(View.GONE);
//mark
final Test test = (Test)marks.get(positioner);
holder.title.setText(test.getName());
holder.total.setText(String.format(ctx.getString(R.string.new_m_sum), test.getMarkGot(), test.getMarkOver()));
//add here
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx,addTest.class);
Test mark = (Test)marks.get(holder.posito);
i.putExtra("t_name",mark.getName());
i.putExtra("subject",mark.getSubject());
i.putExtra("mark_got",mark.getMarkGot());
i.putExtra("mark_over",mark.getMarkOver());
i.putExtra("mode","edit");
i.putExtra("oldId", mark.getId());
ctx.startActivity(i);
}
});
holder.card.setLongClickable(true);
holder.card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final Dialog dialo = new Dialog(ctx);
dialo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialo.setContentView(R.layout.material_dialog);
TextView title = (TextView) dialo.findViewById(R.id.title);
TextView body = (TextView) dialo.findViewById(R.id.body);
Button negative = (Button) dialo.findViewById(R.id.negative);
negative.setText(ctx.getString(R.string.cancel));
Button positive = (Button) dialo.findViewById(R.id.positive);
positive.setText(ctx.getString(R.string.Delete));
title.setText(ctx.getString(R.string.d));
body.setText(ctx.getString(R.string.q_delete) + " " + test.getName() + " " + ctx.getString(R.string.de_comp));
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialo.dismiss();
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vir) {
TestDatabase tb = new TestDatabase(ctx);
SemesterDatabase semesterDatabase = new SemesterDatabase(ctx);
tb.deleteTest(holder.posito, semesterDatabase.getSelected().getName());
MarksAdapter.this.notifyItemRemoved(holder.posito);
marks.remove(holder.posito);
for (int i = 0; i < marks.size(); i++) {
if(!(marks.get(i) instanceof Test)) {
String sub = String.valueOf(marks.get(i));
if(db.isNoValue(sub,selectedSem)){
marks.remove(i);
notifyItemRemoved(i);
}
}
}
dialo.dismiss();
}
});
dialo.show();
return true;
}
});
}else {
holder.group.setVisibility(View.VISIBLE);
holder.card.setVisibility(View.GONE);
//group
if(holder.posito == 0) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)holder.group.getLayoutParams();
params.setMargins(0,0,0,0);
holder.group.setLayoutParams(params);
}
String sub = String.valueOf(marks.get(holder.posito));
holder.groupTitle.setText(sub);
holder.groupMark.setText(db.getTotalSubjectMarks(sub,selectedSem));
}
if(lastPosition < holder.posito) {
if(holder.card.getVisibility() == View.VISIBLE) {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.marks);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 100;
slide.setStartOffset(offset);
holder.card.startAnimation(slide);
} else {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.mark_groups);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 50;
slide.setStartOffset(offset);
holder.group.startAnimation(slide);
}
lastPosition = holder.posito;
}
}
#Override
public int getItemCount() {
return marks.size();
}
}
Note: I already tried the itemViewType method but it didn't work for me
Thanks in advance!
I believe you missed to set holder.card back to visible, like this
if(marks.get(holder.posito).getClass() == Test.class) {
holder.card.setVisibility(View.Visible); //add back this
holder.group.setVisibility(View.GONE);

How to get the position of Item on Click in Android

Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...

Categories

Resources