Search code examples
androidandroid-dialogfragmentdialogfragment

Pass item[] to DialogFragment


I am trying to pass the String [] items of my Dialog Fragment when the activity is running, as this String is updated and its values, which are showing the DialogFragment are updated and can not always choose the same. I have read this topic: stackoverflow but I think that's not exactly what I need. I know someone help me?

This is mi class DialogoSeleccion wich extends DialogFragment:

public class DialogoSeleccion extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final String[] items = {"Español", "Inglés", "Francés"};

        AlertDialog.Builder builder = 
                new AlertDialog.Builder(getActivity());

        builder.setTitle("Selección")
        .setMultiChoiceItems(items, null, 
                new DialogInterface.OnMultiChoiceClickListener() {
        public void onClick(DialogInterface dialog, int item, boolean isChecked) {
                Log.i("Dialogos", "Opción elegida: " + items[item]);
            }
        });

        return builder.create();
    }
}

And this is the code of the main class:

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
DialogoSeleccion dialogo = new DialogoSeleccion();
dialogo.show(fragmentManager, "tagSeleccion");

He probado a poner String[] items como una variable de la clase DialogoSeleccion y luego acceder desde el main de la forma:

public class DialogoSeleccion extends DialogFragment {
    private String[] opciones;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {   
    ...

String[] opciones = {"1","2"}
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
DialogoSeleccion dialogo = new DialogoSeleccion();
dialogo.items= opciones[];
dialogo.show(fragmentManager, "tagSeleccion");

But it doesn't work.

Thanks for your help


Solution

  • You can add a bundle when committing the DialogoFragment

    Bundle bundle= new Bundle();
    bundle.putStringArray(A_KEY,mArray);
    DialogoSeleccion dialogo = new DialogoSeleccion();
    dialogo.setArguments(bundle);
    

    And then you retrieve the bundle arguments in your Dialog

    String[] array = bundle.getArguments().getStringArray(A_KEY);