仅在我在recyclerview中单击的第一个元素时才调用onBindViewHolder

时间:2018-07-26 12:15:38

标签: android android-recyclerview recycler-adapter

我有一个片段,其中有recyclerview并为其设置了适配器。如果我单击第一个添加到购物车,然后单击第二个。此后,片段重新启动时,只会更改首次添加到购物车的状态。同样,如果我在重新启动后首先单击recyclerview中的第二个添加到购物车元素,则仅更改了第二个添加到购物车的状态。我想从0到适配器中的最后一个元素调用onBindViewHolder位置。在ViewHolder类中,有Add_to_cart更改侦听器。

public void onBindViewHolder(@NonNull final MilkAdapter1.ViewHolder holder, int position) {
    // I need to call this method for all elements in recyclerview whenever restarted 
    if (c != null && c.moveToFirst()) {
        do {
            for (int i = 0; i < list.size(); i++) {
                if (name.equals(holder.product_name.getText().toString())) {  // if present just update the AddToCart status
                   // if add_to_cart element is present in sqlite Database, just update its status
                    holder.textView.setVisibility(View.GONE); // this will change the Add to Cart status
                    holder.linearLayout.setVisibility(View.VISIBLE);
                    holder.digit.setText(quantit + "");
                }
            }
        } while (c.moveToNext());
        c.close();
    }

}

抱歉,由于声望较低,我无法将图像上传到我的应用程序。

2 个答案:

答案 0 :(得分:1)

您可以使用不使用for循环的位置来实现此目标。

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


public void onBindViewHolder(@NonNull final MilkAdapter1.ViewHolder holder, int position) {
    // I need to call this method for all elements in recyclerview whenever restarted 
    if (c != null && c.moveToFirst()) {
        do {

                if (name.equals(holder.product_name.getText().toString())) {  // if present just update the AddToCart status
                   // if add_to_cart element is present in sqlite Database just update its status
                    holder.textView.setVisibility(View.GONE); // this will change the Add to Cart status
                    holder.linearLayout.setVisibility(View.VISIBLE);
                    holder.digit.setText(quantit + "");

            }
        } while (c.moveToNext());
        c.close();
    }

}

答案 1 :(得分:0)

假设您将选定的项存储在ArrayList中(如果您不这样做,我鼓励您这样做),则解决方案是:

public void onBindViewHolder(@NonNull final MilkAdapter1.ViewHolder holder, int position) {
    // I need to call this method for all elements in recyclerview whenever restarted 
    if (c != null && c.moveToFirst()) {
        do {
            if (nameArrayList.contains(holder.product_name.getText().toString())) {  // if present just update the AddToCart status
                   // if add_to_cart element is present in sqlite Database just update its status
                holder.textView.setVisibility(View.GONE); // this will change the Add to Cart status
                holder.linearLayout.setVisibility(View.VISIBLE);
                holder.digit.setText(quantit + "");
            }
        } while (c.moveToNext());
        c.close();
    }
}

正如Sachin Soma所指出的,您不需要for循环,因为onBindViewHolder会为列表中的每个项目调用一次。