我正在为我的电子商务应用程序创建Recyclerview,其中在单击“添加到购物车”按钮后,该按钮的布局需要更改为其他布局(某些布局包含文本“添加到购物车”)。我知道该怎么做,但是当我单击“添加到购物车”按钮时,仅当我单击两次时,它才会更改布局。请帮忙。
这是我在Viewholder中编写的代码:
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mproducttext;
public TextView mpricetext;
public ImageView mimageview;
public ImageView mcarticon;
boolean isincart=false;
public ViewHolder(final View itemView) {
super(itemView);
mproducttext = itemView.findViewById(R.id.productnametext);
mpricetext = itemView.findViewById(R.id.pricetext);
mimageview=itemView.findViewById(R.id.productimageview);
mcarticon=itemView.findViewById(R.id.addtocarticon);
mcarticon.setBackgroundResource(R.drawable.addtocarticon);
mcarticon.setOnClickListener(mTogglePlayButton);
mimageview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
ProductResult mProductResult= mArraylist.get(position);
String productname= mProductResult.getProductname();
String price=mProductResult.getPrice();
String imageurl=mProductResult.getImageurl();
Intent intent=new Intent(mcontext,Description.class);
intent.putExtra("productname",productname);
intent.putExtra("price",price);
intent.putExtra("imageurl",imageurl);
mcontext.startActivity(intent);
}
});
}
View.OnClickListener mTogglePlayButton = new View.OnClickListener(){
@Override
public void onClick(View v) {
if(isincart){
v.setBackgroundResource(R.drawable.addedtocarticon);
}else{
v.setBackgroundResource(R.drawable.addtocarticon);
}
isincart = !isincart; // reverse
}
};
}
答案 0 :(得分:0)
在我看来,这是因为您首先检查isincart,然后更改变量的值。尝试将其反转,例如:
View.OnClickListener mTogglePlayButton = new View.OnClickListener(){
@Override
public void onClick(View v) {
isincart = !isincart; // reverse
if(isincart){
v.setBackgroundResource(R.drawable.addedtocarticon);
}else{
v.setBackgroundResource(R.drawable.addtocarticon);
}
}
};