I'm new to Android development and Java and I'm having troubles with Toast:
I have a MainActivity with several buttons. Each one of this starts another Activity with typical setOnclickListener
method like this:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), secondaryActivity.class);
startActivity(intent);
}
});
Then, inside this secondaryActivity.class
I have another button that make some stuff. Inside this Activity I wanna display a Toast on button's click but it doesn't work:
secondaryActivityBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"text",Toast.LENGTH_LONG).show();
}
});
As Toast's context I've tried: getApplicationContext()
, getBasecontext()
, view.getContext()
, mySecondaryActivityClass.this
... No one of this display the Toast, I don't know where's the mistake. Supposedly, view.getContext()
might work but it doesn't display anything...
MainActivity extends AppCompactActivity and mySecondaryActivity extends Activity.
Help please! :( Thanks!
CodePudding user response:
you can use secondaryActivity.this
like:
Toast.makeText(secondaryActivity.this,"text",Toast.LENGTH_LONG).show();
its works only on secondaryActivity class
Good luck and happy coding :-)
CodePudding user response:
Try this:
Toast.makeText(getActivity().getApplicationContext(),"text",Toast.LENGTH_LONG).show();