How to call an alertDialog within a fragment?

0

I can not call an alertDialog inside a fragment. At the time of setting the builder (this) it returns error. Here is the code:

public void mostrarMsg(String titulo, String mensagem) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(titulo);
    builder.setMessage(mensagem);
    builder.show();
}

This code normally works inside an activity when it is called, but when it is placed inside a fragment it returns error in 'this'. What is the reason and how can it be solved?

    
asked by anonymous 28.06.2016 / 14:09

1 answer

3

Change this to getActivity() that will solve your problem.

The reason for this is that it expects you to pass Context in there, a Activity is a Context , because it extends from class Context , so when you use this you're se referring to the current object, in which case its Fragment is not a Context .

See more about context here:

what is a context on Android?

    
28.06.2016 / 14:16