Home » Android » android – Toast in Fragment, should use getActivity() or getAcitivity().getApplicationContext()?

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

Posted by: admin June 15, 2020 Leave a comment

Questions:

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();
}
});
How to&Answers:

For user interface related calls use the Activity context.

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