Question:
My project is spread over several chunks. When clicking on the button of the fragment I get a dialog and I would like that when clicking on the ok button of the dialog it would change the fragment behind it to a different one, how can I do it?
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
for (int i = 0; i<chekedniveles.length; i++){
boolean checked = chekedniveles[i];
if (checked) {
System.out.println(nivelesList.get(i) + "\n");
}
}
I think that to update the fragment it has to go inside the ok button of the listener, but it throws me an error.
Answer:
Since the parent of the dialog is a fragment, you cannot change the fragment from that dialog. FragmentManager
belongs to Activity
. A shard cannot (and should not) remove itself. For the activity is the one who knows and manages all the fragments, including itself.
Suppose your dialog event handling code is in the snippet. You won't be able to change the snippet from that code. You'll need to ask the parent activity to do this. You can use an interface to communicate with the parent activity.
Template code for this interface is included in the code template that Android Studio generates for each fragment. This interface allows you to send messages to the parent activity. It is completely valid to send a self-destruct message.
For example, in the snippet:
public class MiFragmento extends Fragment {
OnDestruir mCallback;
// La actividad padre debe implementar esta interfaz
public interface OnDestruir {
public void onDestruirFragmento(Fragment miFragmento);
// Puedes agregar más si necesitas
}
// El resto del código
}
In the Button Handler :
@Override
public void onClick(DialogInterface dialog, int which) {
// Mucho código por aquí
Fragment.this.mCallback.onDestruirFragmento(this);
}
And in the activity:
public static class MiActividad extends Activity implements MiFragmento.OnDestruir{
// Mucho más código por acá
// Esta es la implementación de la interfaz.
public void onDestruir(Fragment quien) {
/*
* Aquí ya puedes acceder a FragmentManager, destruir 'quien'
* y reemplazarlo por otro, o lo que necesites.
*/
}
}
You must ensure that the activity implements the interface. The Android Developersdocumentation in English has more information on this.