【问题标题】:While Scrolling RecyclerView, custom-view value keep changing滚动 RecyclerView 时,自定义视图值不断变化
【发布时间】:2017-03-11 08:33:28
【问题描述】:

我有一个问题,当我点击增加第一个项目的位置数量时,当我向下和向上滑动时,该项目的位置闪烁......

请帮帮我提前谢谢

这是我的适配器类。

package growcia.malacus.com.growcia.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

 import java.util.List;

 import growcia.malacus.com.growcia.R;
 import growcia.malacus.com.growcia.activity.ProductListActivity;
 import growcia.malacus.com.growcia.database.SqliteDatabaseClass;
 import growcia.malacus.com.growcia.model.SellerProductPOJO;



 public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.ViewHolder> {

public Context context;
SqliteDatabaseClass DB;
String productCode;
boolean isPressed = false;
int count = 0;
int qty;


public String pname, price, img_path;
static int productItem = 0;
int totPrice;

ProductListActivity objProductList;
List<SellerProductPOJO> productListDetails;


public ProductListAdapter(List<SellerProductPOJO> productDetails, Context context) {
    super();

    DB = new SqliteDatabaseClass(context);
    objProductList = new ProductListActivity();
    this.productListDetails = productDetails;
    this.context = context;
}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_product, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    final SellerProductPOJO objSellerProductPOJO = productListDetails.get(position);

    try {
        JSONArray jar = DB.getAllProductCodeAndQtyProductList();
        Log.e("total pid and qty ad : ", "" + jar.toString());

        for (int i = 0; i < jar.length(); i++) {
            JSONObject job = jar.getJSONObject(i);

            String cart_productId = job.getString("ProductCode");
            String productQty = job.getString("QuantityOrdered");

            Log.e("id and qty: ", cart_productId + " qty: " + productQty);

            String plist_prod_id = productListDetails.get(position).getProductCode();

            Log.e("product id in cart : ", "" + cart_productId.toString());
            Log.e("product id service : ", "" + plist_prod_id.toString());

        }

    } catch (JSONException J) {
        J.printStackTrace();
    }


    String url = objSellerProductPOJO.getImagePath();
    Picasso.with(context)
            .load(url)
            .placeholder(R.drawable.placeholder)   // optional
            .error(R.drawable.error)   // optional
            .resize(100, 100)                        // optional
            .into(holder.ivProduct);
    holder.tvProductName.setText(objSellerProductPOJO.getProductName());
    holder.tvUnit.setText(objSellerProductPOJO.getAvailableQuantity());
    holder.tvPrice.setText(objSellerProductPOJO.getPrice());

    Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/abc.ttf");
    holder.tvProductName.setTypeface(font);
    holder.tvUnit.setTypeface(font);
    holder.tvPrice.setTypeface(font);


    if (context instanceof ProductListActivity)
        totPrice = DB.getSumPrice();
    Log.e("all price insert : ", "" + totPrice);
    count = DB.getProfilesCount();
    Log.e("count from db", "" + count);
    ((ProductListActivity) context).showCartItem(count, totPrice);



    holder.btnPlus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            SellerProductPOJO objSellerProduct = productListDetails.get(position);


            String stock = holder.tvUnit.getText().toString();
            int qtyMiddle = Integer.parseInt(holder.tvQty.getText().toString());
            int qtyStock = Integer.parseInt(objSellerProduct.getAvailableQuantity().toString());


            if (!stock.equalsIgnoreCase("0")) {

                if (qtyMiddle < qtyStock) {


                    pname = objSellerProduct.getProductName();
                    img_path = objSellerProduct.getImagePath();
                    price = objSellerProduct.getPrice();
                    productCode = objSellerProduct.getProductCode();


                    String str_qty = holder.tvQty.getText().toString();
                    int qty = Integer.parseInt(str_qty);

                    qty = qty + 1;
                    String final_str_qty = "" + qty;


                    objSellerProductPOJO.setQty(final_str_qty);
                    holder.tvQty.setText(objSellerProductPOJO.getQty() + "");

                    int reduceable_stock = qtyStock - qty;

                    holder.tvUnit.setText(reduceable_stock + "");

                    if (qty > 0) {
                        boolean entryStatus = DB.Exists(productCode);
                        if (entryStatus) {

                            productItem = productItem + 1;
                            String str_newQty = holder.tvQty.getText().toString();
                            int newqty = Integer.parseInt(str_newQty);
                            double intPrice = Double.parseDouble(price);
                            double totPrice = qty * intPrice;
                            DB.updateProductQty(productCode, newqty, totPrice);
                            totPrice = DB.getSumPrice();
                            Log.e("all price update: ", "" + totPrice);

                        } else {
                            productItem = 1;
                            DB.addProductItem(productCode, pname, img_path, productItem, price, price);

                        }
                        if (context instanceof ProductListActivity)
                            totPrice = DB.getSumPrice();
                        Log.e("all price insert : ", "" + totPrice);
                        count = DB.getProfilesCount();
                        Log.e("count from db", "" + count);
                        ((ProductListActivity) context).showCartItem(count, totPrice);
                    }


                } else {
                    Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
                }

            }

        }
    });

    holder.btnMinus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String stock = holder.tvUnit.getText().toString();
            if (!stock.equalsIgnoreCase("0")) {

                SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);

                String str_qty = holder.tvQty.getText().toString();
                int qty = Integer.parseInt(str_qty);

                if (qty != 0) {

                    int qtyStockMinusClick = Integer.parseInt(holder.tvUnit.getText().toString());

                    holder.tvUnit.setText((qtyStockMinusClick + 1) + "");



                    Log.e("btnMinus", "" + qty);

                    if (qty == 1) {
                        Log.e("", "inside 0 qty");
                        DB.delete_byID(productCode);
                        qty = qty - 1;
                        String final_str_qty = "" + qty;

                        objSellerProductPOJO.setQty(final_str_qty);
                        holder.tvQty.setText(objSellerProductPOJO.getQty()+"");


                    } else {

                        qty = qty - 1;
                        String final_str_qty = "" + qty;

                        objSellerProductPOJO.setQty(final_str_qty);
                        holder.tvQty.setText(objSellerProductPOJO.getQty()+"");


                        double intPrice = Double.parseDouble(price);
                        double totPrice = qty * intPrice;

                        DB.updateProductQty(productCode, qty, totPrice);
                    }

                    if (context instanceof ProductListActivity)
                        totPrice = DB.getSumPrice();
                    Log.e("all price insert : ", "" + totPrice);
                    count = DB.getProfilesCount();
                    Log.e("count from db", "" + count);
                    ((ProductListActivity) context).showCartItem(count, totPrice);

                }
            } else {
                Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
            }
            notifyDataSetChanged();
        }
    });


    holder.imagefavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.e("position", "all position" + position);
            if (isPressed)
                holder.imagefavorite.setBackgroundResource(R.drawable.ic_not_favourite);
            else
                holder.imagefavorite.setBackgroundResource(R.drawable.favourite_icon);

            isPressed = !isPressed;
        }
    });

}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}


@Override
public int getItemCount() {
    return productListDetails.size();
}



class ViewHolder extends RecyclerView.ViewHolder {

    public TextView tvProductName;
    public TextView tvUnit;
    public TextView tvPrice;
    public TextView tvQty;
    public ImageView ivProduct;
    public ImageView imagefavorite;
    //  public EditText edqntiry;
    public Button btnPlus;
    public Button btnMinus;

    public ViewHolder(View itemView) {
        super(itemView);
        ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
        tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
        tvUnit = (TextView) itemView.findViewById(R.id.tvUnit);
        tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
        tvQty = (TextView) itemView.findViewById(R.id.tvQty);
        btnPlus = (Button) itemView.findViewById(R.id.btnPlus);
        btnMinus = (Button) itemView.findViewById(R.id.btnMinus);
        imagefavorite = (ImageView) itemView.findViewById(R.id.imagefavorite);
    }

}
}

当我要增加数量时,屏幕下方会显示

当我向下和向上滚动时,屏幕下方会显示

【问题讨论】:

  • 你是什么意思那个项目的位置在晃动
  • 看上面两张图...
  • 第一张图片在滚动之前,下一张是在滚动之后
  • 这是一个简单的例子,RecyclerView 重用了它创建的Views (ScrappedViews)。因此,只需将您的数据重新绑定到 holder.tvQty 即可解决问题。正如@user6709464 所建议的那样。我还鼓励您不要在onBindView() 中添加/创建新侦听器(每次滚动到新视图时都会创建一个新实例)。将它们放在 ViewHolder 中。
  • 我已经更新了同样的..

标签: android android-studio android-fragments android-recyclerview


【解决方案1】:

在您的 onClick() 方法中,将 onBindViewHolder() 方法的 position 参数替换为 getAdapterPosition()

替换自

SellerProductPOJO objSellerProduct = productListDetails.get(position);
SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);

SellerProductPOJO objSellerProduct = productListDetails.get(getAdapterPosition());
SellerProductPOJO objSellerProductDeduct = productListDetails.get(getAdapterPosition());

【讨论】:

    【解决方案2】:

    您需要在添加或减去之后更新 productListDetails 变量

    holder.tvQty.setText(final_str_qty);

    并使用 notifydatasetchange() 通知适配器

    【讨论】:

      【解决方案3】:

      您没有在 onBindViewHolder 方法中设置 holder.tvQty 的初始值。

      当您在 holder.btnPlus 或 holder.btnMinus 侦听器中更新 holder.tvQty 的值时,您应该将该值保存在 objSellerProductPOJO 中的某个位置:

      objSellerProductPOJO.setQty(final_str_qty)
      

      然后在:

      holder.tvPrice.setText(objSellerProductPOJO.getPrice());
      

      添加:

      holder.tvQty.setText(objSellerProductPOJO.getQty());
      

      【讨论】:

      • 欢迎您。您能用您尝试的方法更新您的问题吗?
      • 好的,谢谢。你能告诉我如何初始化吗?请
      • holder.tvQty.setText("插入保存的值");
      • 谢谢 Elias N... 我已经在我想要 getQty() 的类中初始化了 qty。
      • @ Elias N. 我也有同样的问题。但不能应用此解决方案。 [链接] (stackoverflow.com/q/67245065/14253444)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2012-07-05
      • 1970-01-01
      相关资源
      最近更新 更多