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();
}
});
This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.
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.
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.
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.
For user interface related calls use the Activity context.
See this explanation by Reto Meier: https://stackoverflow.com/a/987503/534471
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