Reputation: 1
I want to know the difference between the two contexts in the two Toasts below , when to use this & when to use getActicity ?
Toast.makeText(getActivity() , "Text" ,Toast.LENGTH_LONG).show();
Toast.makeText(this , "Text" ,Toast.LENGTH_LONG).show();
Upvotes: 0
Views: 217
Reputation: 151
To create a Toast
you need a Context
object.
If you are in an Activity
class or another class that extends the Context
class you can use this
(because the Activity
is itself a Context
child )
If you are for example in a Fragment
class, that doesn't extends Context
, you should use getActivity()
to get a Context
reference.
Here the docs about the Context
class where you find all the classes that extends it : http://developer.android.com/reference/android/content/Context.html
Upvotes: 1
Reputation: 14810
this
is actually a pointer that refers to the current class that you are in. this
can refer to anything like Activity
, Fragment
, View
, etc.A reference of the current object is passed while this
is used.
getActivity()
is available only in the Fragment
class and any other class extending Fragment
and this method returns an object of the type Activity
.
Upvotes: 1
Reputation: 7560
You can specify your Context
with this
or getApplicationContext()
with Activities.
getActivity()
is used with Android Fragments
Upvotes: 1
Reputation: 2075
If you say are trying to access it from a Fragment
, use getActivity()
else if you are in Activity
itself, use this
.
Upvotes: 1