Use Toast in Activity
This is the most basic use of toast, the first parameter is the context, generally in the activity we use this instead, representing the caller's instance as activity.
Public classTestdbactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub Super. OnCreate (savedinstancestate); Setcontentview (R.LAYOUT.TESTDB2); Toast.maketext ( This, "Welcome to Concise modern Magic ~", Toast.length_short). Show (); //Toast.maketext (Getapplicationcontext (), "Welcome to Concise modern Magic ~", Toast.length_short). Show (); }}
It is also possible to replace this with Getapplicationcontext ().
and to a button of the onclick (view view) and other methods, we use this when the error, So we might use activityname.this to solve the problem, mainly because the class that implements the context has several models specific to Android, Activity, service, and Broadcastreceiver.
Use Toast in Fragment
In Fragment, you need to use getactivity () to get the Context object, as follows:
Public class extends Fragment { @Override publicvoid onCreate (Bundle savedinstancestate) { Super. OnCreate (savedinstancestate); " Welcome to Concise Modern Magic ~ ", Toast.length_short). Show (); })
Use Toast in non-activity/fragment
If you want to use a Toast in a class other than activity/fragment, you still use This/getapplicationcontext (), you will generally report such a mistake:
The method Getapplicationcontext () is undefined
Because the context is not available, how do you get to it in this class? You can pass the Context over.
When instantiating a class, the Context is passed as a parameter:
New MyClass (this);
Then write a constructor that receives the Context as a parameter.
Public class MyClass { Context C; Public MyClass (Context context) { = context; }}
You can then use the Toast:
Public void onproviderdisabled (String provider) { "Gps Disabled", Toast.length_short);}
Turn from: Institute of Modern Magic
Use toast "Go" outside activity/fragment