NiceToMytyuk
NiceToMytyuk

Reputation: 4287

How to callback different clicks from DialogFragment to Activity?

I have a DialogFragment with a RecyclerView where i can click some items, that items have to be added to the "Parent" item from the Activity and i have other 4 buttons which do different stuff in that Dialog.

How can i manage the clicks from RecyclerView and from Buttons in my Activity?

Like my Dialog looks like this:

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());

    final Comanda prodotto = (Comanda) getArguments().getSerializable("PRODOTTO");
    final int menuSelezionato = getArguments().getInt("ACTIVE_MENU");

    List<Varianti> variantiAggiunte = prodotto.getVarianti();


    DataBaseHandler dbContext = DataBaseHandler.getInstance(requireActivity());
    ArrayList<VariantiBinding> variantiList = dbContext.getVarianti();
    ArrayList<VariantiBinding> variantiFilteredList = selectVariantiByMenu(variantiList, menuSelezionato);

    AdapterVariantiAggiunte adapterVariantiAggiunte = aggiunteRecycler(recyclerVariantiAdded, variantiAggiunte);
    AdapterVarianti adapterVarianti = variantiRecycler(recyclerVarianti, variantiFilteredList);

    title.setText(prodotto.getDescrizione());

    builder.setView(view);

    adapterVarianti.setOnItemClickListener(positionVariante -> {
        search.clearFocus();
        VariantiBinding varianteSelezionata = adapterVarianti.getList().get(positionVariante);
        Varianti variante = getVariante(varianteSelezionata);
        if (variante != null) {
            //adapterComanda.addVariante(variante); adapterComanda is in Activity
            adapterVariantiAggiunte.notifyItemInserted(adapterVariantiAggiunte.getItemCount() - 1);
            recyclerVariantiAdded.scrollToPosition(adapterVariantiAggiunte.getItemCount() - 1);
        }
    });
    
    return builder.create();
}

I have to handle the adapterVarianti click in both VariantiDialog and in My Activity, for now only the click in Dialog is handled but like i need to get something like a callback in my Activity and call:

adapterComanda.addVariante(variante);

Before all that was at the same level but i had all my AlertDialogs in my Activity and i'm moving them to DialogFragment.

Upvotes: 0

Views: 1006

Answers (1)

Nitish
Nitish

Reputation: 3411

You can use interface to give callbacks, one for dialog frgament to activity and one from recyclerview to dialog fragment

1 Interface (for callback from dialog fragment to acitvity)

public interface OnDialogCountryChangeListener {
    public void onDialogCountryChange(String country);
}

2 Activity.java (class starting the dialog fragment)

public class MyActivity extends AppCompactActivity implements OnDialogCountryChangeListener {
    
    ...

    private void showDialog() {
        FragmentManager fm = getSupportFragmentManager();
        CountryDialogFragment countryDialog = new CountryDialogFragment();
        countryDialog.setTargetFragment(this, 0); // set target fragment for callback listener
        countryDialog.show(fm, "add_dialog");
    }

    @Override
    public void onDialogCountryChange(String country) {
        // Your callback from dialog fragment to activity
        // Do your stuff
    }
}

3 CountryDialogFragment.java

 @Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);

       try {
            countryActivitycallback = (OnDialogCountryChangeListener) getTargetFragment(); // callback instance 
        } catch (ClassCastException e) {
            throw new ClassCastException("Calling Fragment must implement OnDialogCountryChangeListener"); 
        }
 }

For callback from recyclerview to dialog fragment

1 Create interface (You could also use the same interface, but I think it's better to explain using new different one, as it might become confusing)

public interface OnItemClickListener {
     void onItemClick(String countryItem);
 }

2 Next modify your Adapter class , in your case RecycleView Adapter

i) Send listener as a parameter in your constructor

private final OnItemClickListener listener;
public RecycleViewCountryAdapter(OnItemClickListener listener) {
         this.listener = listener;
     }

ii) Set onCLick listener on some view in your ViewHolder class

public MyViewHolder(View itemView) {
         super(itemView);
         imageOnCard = (ImageView) itemView.findViewById(R.id.image_on_cardview);
         // change your listener on any other view if you want
         imageOnCard..setOnClickListener(new View.OnClickListener() {
                 @Override public void onClick(View v) {
                       listener.onItemClick(worldDataModelArrayList.get(getAdapterPosition()));
                 }
        });

     }

3 Now modify your DialogFragment class to listen to your interface callback ,

 recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
 RecycleViewCountryAdapter adapter = new RecycleViewCountryAdapter(new OnItemClickListener() {
     @Override public void onItemClick(String countryItem) {
        // implement click listener as per your requirement

       // handle your work in dialog fragment and also give callback to activity
     if(countryActivitycallback!=null) // callback for activity
       {
                countryActivitycallback.onDialogCountryChange(countryItem);
        }

     });
 recyclerView.setAdapter(adapter);

Edit: setTargetFragment is deprecated now. As a Alternate way you can do the same with a shared ViewModel or with the new API FragmentResultListener.

Upvotes: 1

Related Questions