How to call a alertDialog within a Fragment?

Asked

Viewed 668 times

0

I cannot call a alertDialog inside a Fragment. At the moment of setting the Builder(this) it returns error. Follows 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 returns error in 'this'. What is the reason and how it can be solved?

  • 1

    Puts the Getactivity() that will suit this, it will return to Activity that the Fragment is contained.

1 answer

3


Exchange the this for getActivity() that will solve your problem.

The reason is that he expects you to pass one Context in there, a Activity is a Context, for she extends from the class Context, then when you use the this you are referring to the current object, in your case Fragment is not a Context.


See more about context here:

What is a context on Android?

  • Right, but how do I call this method that is inside the Fragment through a button that is inside it? It is possible to do this by java only?

  • I didn’t understand, in the question you said that this code was not working in a Fragment and error was found in this. For this just replace the this for getActivity() to obtain the contextof Activity.

  • Yes... I managed to do this.. Now my intention is to call this method through a button that is in the xml of Fragment. Now in fact the doubt would be another rs. How can I then, since I managed to create this method inside Fragment, put it on the onclick of a button that is inside Fragment understood? I would like to do this for java and not XML.

  • As it is a totally different context from your question, it would be interesting to create a new one with this click doubt, because there is none currently on the site.

  • OK thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.