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() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).
getActivity(); is a method of android Fragment, if you want to show dialog in your activity, just pass this of your activity instead of getActivity() . Show activity on this post. getActivity() is the member method of the super class Activity that you extend from . It is defined in the Activity class itself.
getContext() - Returns the context view only current running activity. getActivity()- Return the Activity this fragment is currently associated with. getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .
getActivity() is a method that belongs to the Fragment or FragmentCompat classes (check those classes in the Android API), all it does is get a reference to the context of the activity the fragment is attached to.
The getActivity()
method gives the context of the Activity. You can use YourActivityName.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
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivityName.this);
or if you are writing the code in your activity itself even
AlertDialog.Builder builder = new AlertDialog.Builder(this);
will workout. Please feel free to ask any doubts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With