Send a Boolean from an adapter to its fragment

1

I have a problem, maybe you can help me, in the onclick event of a recycler I want to send a boolean to its fragment to update a method, but I do not know how to do it.

before I had done it but not with an adapter from a fragment, this is the adapter code that worked for me before. Adapter

  holder.btMinus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
  ((ActividadPrincipal) view.getContext()).updateItemCount(true);
 }

and I received it in the main activity in this way:

     public void updateItemCount(boolean ifIncrement) {
    if (Common.cartRepository.countCartItems()==0) {

      //  Linearlayoutvacio.setVisibility(View.VISIBLE);
     //Linearlayoutlleno.setVisibility(View.INVISIBLE);
        }

try to do it in the same way by sending a bollean to its fragment changing only "Main Activity" for "My fragment" but it does not work.

((Selection2) view.getContext()).updateItemCount(true);  ----AQUI OCACIONO EL ERROR NO ME DEJA COLOCAR "Seleccion 2"EL CUAL ES MI FRAGMENT

I appreciate your help.

    
asked by IGr135 25.10.2018 в 02:24
source

1 answer

1

Use a callback

Create a interface with your method.

interface TuCallback{
    void updateItemCount(boolean b);
}

Implement your fragment .

class TuFragment extends Fragment implements TuCallback{

    @Override
    public void updateItemCount(boolean b){
        ...
    }
}

Pass it to your adapter , and in the onClick you use the callback .

class TuAdapter extends Adapter{
    private TuCallback callback;

    public TuAdapter(TuCallback callback){
        this.callback = callback;
    }

    ...

    holder.btMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 callback.updateItemCount(true);
            }
}
    
answered by 25.10.2018 в 13:28