Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActivity() where it is defined?

Tags:

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.

like image 1000
sriram Avatar asked Jan 23 '13 12:01

sriram


People also ask

What is getActivity ()?

getActivity() in a Fragment returns the Activity the Fragment is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).

How do you use 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.

What is the difference between getActivity and getContext?

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 .

Which of the following option represents the API to which getActivity () method belongs?

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.


1 Answers

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

like image 81
pvn Avatar answered Oct 06 '22 23:10

pvn