从onBindViewHolder中的RecyclerView更改项目

时间:2018-01-05 15:33:11

标签: java android android-recyclerview adapter

在我的onBindViewHolder我设置setImageResource

holder.card_image.setImageResource(image);

但我的商品可以购买,我可以在holder.view.setOnClickListener()

购买
 bp.purchase((Activity) mContext,model.getProduct_id());

所以,它采用这种方法:

bp = new BillingProcessor() new BillingProcessor.IBillingHandler() {
            @Override
            public void onProductPurchased(@NonNull String productId, @Nullable TransactionDetails details) {
                showToast("onProductPurchased: " + productId);
                //Purchased OK
                //WANT TO CHANGE THE IMAGE ONCE PURCHASE IS OK


            }
            @Override
            public void onBillingError(int errorCode, @Nullable Throwable error) {
                showToast("onBillingError: " + Integer.toString(errorCode));
            }
            @Override
            public void onBillingInitialized() {
                showToast("onBillingInitialized");
                readyToPurchase = true;

            }
            @Override
            public void onPurchaseHistoryRestored() {
                showToast("onPurchaseHistoryRestored");
                for(String sku : bp.listOwnedProducts())
                    Log.d("skuProducts", "Owned Managed Product: " + sku);
                for(String sku : bp.listOwnedSubscriptions())
                    Log.d("skuProducts", "Owned Subscription: " + sku);

            }
        });

如果我不是onBindViewHolder

,如何更改呢?

我的适配器看起来像:

FirebaseRecyclerAdapter adapter = new   FirebaseRecyclerAdapter< CardPOJO, CardHolder>(options) {
        @Override
        public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //inflate the single recycler view layout(item)
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_product, parent, false);
            int width = parent.getMeasuredWidth() / 2;
            width -= mContext.getResources().getDimensionPixelSize(R.dimen._8sdp);
            final CardHolder cardViewHolder = new CardHolder(view,width);
            return cardViewHolder;
        }

        @Override
        public void onDataChanged() {
            super.onDataChanged();
            tv.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE);
        }

        @Override
        protected void onBindViewHolder(CardHolder holder, int position, final CardPOJO model) {
            holder.state.setText(model.getState());
            holder.cardName.setText(model.getName());
            switch (model.getState()){
                case "free":
                    //Img free
                    break;
                case "not_free":
                    //Img not free
                    break;
                default:
                    break;
            }
            holder.view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(model.getState().equals("free")){
                       //stuff
                    }
                    else{
                       //stuff
                        }
                        root_ref.child("PurchasedProducts").child(currentuser).addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                bp.purchase((Activity) mContext,model.getProduct_id()); //HERE I CALL THE PURCHASE SO IF IT'S OK I WANT TO DO SOMETHING LIKE holder.card_image.setImageResource(image);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
                    }

                }
            });


        }
    };
    adapter.startListening();
    products_recycler.setAdapter(adapter);

2 个答案:

答案 0 :(得分:1)

如果我假设正确,您希望更改视图外观或某些图像更改,如果某些付款成功或失败。

为此,你可以有一个回调,它可以让你在活动或片段中找到项目位置,你可以通过服务器调用来进行购买,如果一切顺利的话。 / p>

当您使适配器构造函数传递回调

8+"ab";

所以当你调用你的 obj.notifyDataSetChanged(); 时,它会让适配器再次绘制所有视图,你可以根据点击回调的int位置设置一些标志,并相应地改变它

编辑=&gt; 07/12/2018 :尝试使用Firebase适配器并进行了一些更改,因为代码不足以复制方案但我已经对示例类进行了一些更改,但是基本想法如下。

1:当用户点击onBindViewHolder中的视图时,我们会收到一个回调函数,它在我们调用的片段或活动中给出一个位置参数

2:现在我们处理付款,完成后我们还会通过将CardPojo更新为该特定用户项的服务器来对Database firebase进行更改。

3:当我们更新服务器上的CardPojo时,我们还在card pojo中设置了一个标志,这是paySuccess的一个布尔值,付款完成时将为true。

4:由于我们的付款完成并与服务器同步,现在我们可以调用final SomeAdapter obj = new SomeAdapter(this,new Callback(){ @Override onPaymentRequested(int position, View view){ //this will get called when you press click on image in bindviewholder bp = new BillingProcessor() new BillingProcessor.IBillingHandler() { @Override public void onProductPurchased(@NonNull String productId, @Nullable TransactionDetails details) { showToast("onProductPurchased: " + productId); //Purchased OK adapterModelList.get(position).setPayment(true); obj.notifyDataSetChanged(); } @Override public void onBillingError(int errorCode, @Nullable Throwable error) { showToast("onBillingError: " + Integer.toString(errorCode)); } @Override public void onBillingInitialized() { showToast("onBillingInitialized"); readyToPurchase = true; } @Override public void onPurchaseHistoryRestored() { showToast("onPurchaseHistoryRestored"); for(String sku : bp.listOwnedProducts()) Log.d("skuProducts", "Owned Managed Product: " + sku); for(String sku : bp.listOwnedSubscriptions()) Log.d("skuProducts", "Owned Subscription: " + sku); } }); } }); recyclerView.setAdapter(obj); ,这将从服务器获取我们在回调时收到的特定位置的lates更新。< / p>

5:现在populateViewHolder()为您提供了一个cardpojo对象,您可以检查付款是否已完成然后您可以更改图像

所以这里是涉及的示例代码我试图充分匹配场景,希望您了解我在这里尝试做什么。

首先创建一个监听器或一个回调

firebaseRecycler.notifyItemChanged(position);

现在不是在活动或片段中初始化 FirebaseRecyclerAdapter 而只是创建一个类并扩展它,这将分离你的ui逻辑,并为我们提供了添加回调等额外功能的可扩展性。

public interface CallBackInterface  {
    void onClick(int position,CardPOJO cardPOJO);
}

}

现在几乎一切都已完成,我们需要调用此自定义Firebase适配器并传递所需的内容,它将完成其工作。

public class FirebaseRecycler extends FirebaseRecyclerAdapter<CardPOJO,CardHolder> {

CallBackInterface callBackInterface;

public FirebaseRecycler(Class<CardPOJO> modelClass, int modelLayout, Class<CardHolder> viewHolderClass, DatabaseReference ref) {
    super(modelClass, modelLayout, viewHolderClass, ref);
    this.callBackInterface = callBackInterface;
}

public FirebaseRecycler(Class<CardPOJO> modelClass, int modelLayout, Class<CardHolder> viewHolderClass, Query ref) {
    super(modelClass, modelLayout, viewHolderClass, ref);
    this.callBackInterface = callBackInterface;
}

@Override
public CardHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //your inflater logic goes here
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_product, parent, false);
    CardHolder cardHolder = new CardHolder(view);
    return cardHolder;
}

@Override
protected void populateViewHolder(CardHolder viewHolder, final CardPOJO model, final int position) {
    //your populate logic
    //your existing code here

    if (model.isPaymentDone){
        //set payment success image holder.card_image.setImageResource(image);

    }else{
        //set payment failure image

    }

    //setting the card click listener
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we have the card click listener, we will start the payment processing in activity
            callBackInterface.onClick(position,model);
        }
    });
}

public void setCallBackInterface(CallBackInterface callBackInterface) {
    this.callBackInterface = callBackInterface;
}

这演示了您可以根据自己的要求修补它的基本逻辑。

答案 1 :(得分:0)

url(...)的适配器获取您的项目并进行编辑。然后只需拨打RecyclerView,这将导致专门为该位置调用Adapter.onItemChanged(int position)