Search code examples
androidlistcallbackdialogfragment

How can i get data back from this dialog fragment in this code?


I have tried, but doesn't work. Let me show more details ok?

I have this on my activity:

mainActivity

xTipo.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        new ListTipo().show(getSupportFragmentManager(),"ListTipo");
    }
});

And i have this java code to my DialogFragment

Dialog Fragment:

public class ListTipo extends DialogFragment {
    
        @NonNull
        @Override
        public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) 
         {
    
            int style = DialogFragment.STYLE_NORMAL, theme = 0;
            theme = R.style.dTheme;
            setStyle(style, theme);
            String [] tipos = getActivity().getResources().getStringArray(R.array.tipo_atendimento);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), theme);
            builder.setTitle("\b\b\bTipo de Atendimento");
            builder.setItems(tipos, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        return builder.create();
    }
}

This work fine, but I can't pick up the result. Thank you for your time and patient!


Solution

  • Create a callback interface, implement it on your code (where you set up the listeners), then pass it as a parameter in the dialog.

    Example:

    public interface Callback {
        void onResult(Object result);
    }
    
    private Callback callback;
    public void setCallback(Callback callback) {
        this.callback=callback;
    }
    
    // where you want to pass the result
    if(callback!=null)
        callback.onResult(YOUR_RESULT);
    

    Where you create the dialog:

    xTipo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ListTiop fragment=new ListTipo();
            fragment.setCallback(result -> {
                // run your code with the result
            });
            fragment.show(getSupportFragmentManager(),"ListTipo");
        }
    });