Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast in Fragment, should use getActivity() or getAcitivity().getApplicationContext()?

Tags:

android

Sorry for my newbie Question, i just cannot find the answer from google and stackoverflow.. i just start learning for android, wish can build a good base for android knowledge. I wondering which i should use in the following if i create toast.maketext in fragment. getActivity() or getAcitivity().getApplicationContext()?

i did try both, it works well..

btn1.setOnClickListener(new View.OnClickListener() {            
@Override
public void onClick(View v) {
 Toast.makeText(getActivity(), "hello",Toast.LENGTH_LONG).show();
 Toast.makeText(getActivity().getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
}
});
like image 549
NaiveBz Avatar asked Feb 22 '13 02:02

NaiveBz


People also ask

How do you make toast in fragments?

This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.

What is the difference between getActivity and Getcontext?

getActivity() is at least a method on Fragment, to get the activity it is attached to. Whenever a context is needed in an instance method of an activity, you can use this . A context is needed whenever contextual info is needed, or when stuff needs to be displayed.

How do you show toast in fragment in Kotlin?

You can use the makeText() method to instantiate a Toast object: The application or activity Context . The text to appear on the screen to the user. The duration to show toast on screen.

How do I pass context from activity to fragment?

Instead of passing around the application context, create a static context inside your Application class and initialize it onCreate(): MyApplication. sContext = getApplicationContext(); then you can access it from any activity/fragment without worrying about detachment. @milaniez: getActivity has always been available.


1 Answers

For user interface related calls use the Activity context.

See this explanation by Reto Meier: https://stackoverflow.com/a/987503/534471

like image 169
Emanuel Moecklin Avatar answered Oct 12 '22 06:10

Emanuel Moecklin