Ivan Zolotarov
Ivan Zolotarov

Reputation: 321

Creating Alert Dialog object

I understand how to create an AlertDialog object and how to add elements, but i can't understant what is getActivity() method, and how can i get it?

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

Upvotes: 0

Views: 552

Answers (2)

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20626

First you should read getActivity() from documentation.

getActivity() can be used in Fragments and it returns :

Return the Activity this fragment is currently associated with.

This method is created to get the current Activity

Why you need it to create a dialog?

As you can see the constructor of AlertDialog requires a context then you have to pass the getActivity()

But why am i getting "The name "getActivity" does not exist in the current context"?

If you are not in a Fragment you don't have to call getActivity() you can use this to pass the context of its Activity

Example

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

Upvotes: 2

SushiHangover
SushiHangover

Reputation: 74164

The AlertDialog.Builder constructor is looking for a context so in Xamarin you can pass it this for the current activity assuming you are already within an Activity.

var builder = new AlertDialog.Builder(this);
builder.SetTitle("My Custom Alert").SetMessage("StackOverflow").Create().Show();

enter image description here

Upvotes: 1

Related Questions