I'm trying to show a Toast Message when user click on a Button inside a Fragment. The problem is I cannot access the activity to show the Toast on it.
Here's the source of Fragment
:
public class FrgTimes extends Fragment
{
ScrollView sv;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
if (container == null) { return null; }
sv = (ScrollView)inflater.inflate(R.layout.frg_times, container, false);
btnTime1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//****** HERE's the PROBLEM ********
Toast.makeText(<The Activity>, "Please long press the key", Toast.LENGTH_LONG );
}});
return sv;
}
and Here's what I've been tried.
Toast.makeText( getActivity() , ...
Toast.makeText( getView().getContext() , ...
Toast.makeText( getActivity().getApplicationContext() , ...
Toast.makeText( sv.getContext() , ...
Toast.makeText( sv.getRootView().getContext() , ...
In Debug I can see that all of these codes run without any exception but no TOAST
being displayed.
This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast.
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.
If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .
You are not calling show()
on the Toast
you are creating with makeText()
.
As stated by alfo888_ibg:
@Override public void onClick(View arg0) { Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show(); }
Just do:
Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
this worked for me.
To help another people with my same problem, the complete answer to Use Toast inside Fragment is:
Activity activity = getActivity();
@Override
public void onClick(View arg0) {
Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}
When making a toast in fragment do as following:
Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();
When class is extending fragment it is necessary to use getActivity() since fragment is a subclass of activity.
Cheerse
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