I'm very new to android and I'm following this example.
The code says we need to do these steps to get an dialog box:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
But where does the getActivity()
method is defined?
I can't find that method.
getActivity when you use then no need to put new... such as
user it as :
here we remove new that provide new allocation but here it provide its allocation via getActivity in with in Activity(this).
getActivity()
is the member method of the super class Activity that you extend from . It is defined in the Activity class itself. infactonCreate()
,onPause()
and all other functions are themselves also defined in the parent Activity Class.The constructor
AlertDialog.Builder
expects aContext
parameter.Context
is accessible fromActivity
,Service
etc, since they allextend
Context
, and can be passed asthis
.The method
getActivity()
is declared as others have mentiond in theFragment
class.The
getActivity()
method gives the context of the Activity. You can useYourActivityName.this
instead of it.The method
getActivity()
is normally used in fragments to get the context of the activity in which they are inserted or inflated.eg
or if you are writing the code in your activity itself even
will workout. Please feel free to ask any doubts
This article describes how to create an
AlertDialog
in aFragment
. in Fragments, you can get the correspondingActivity
by callinggetActivity()
method. but in your case i assume you are doing this in anActivity
. so you don't have to callgetActivity()
. just usethis